From 0dc7d288515e0bdf309d14add17ccd28a34491ac Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 10:18:22 +0100 Subject: [PATCH 001/109] Initial Update to forge 1.8 --- .gitignore | 3 +++ build.gradle | 1 + build.properties | 7 ++++--- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 6599da67..102fb408 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ bin /Deploy.bat /FixDependicies.bat /Install Forge.bat +.nb-gradle +.nb-gradle-properties +eclipse diff --git a/build.gradle b/build.gradle index 466fafc4..1ee26304 100644 --- a/build.gradle +++ b/build.gradle @@ -42,6 +42,7 @@ version = "${project.config.mod_version}" minecraft { version = config.mc_version + "-" + config.forge_version runDir = "eclipse" +mappings = config.mcp_version } diff --git a/build.properties b/build.properties index 3954bd92..0c869281 100644 --- a/build.properties +++ b/build.properties @@ -1,3 +1,4 @@ -mc_version=1.7.10 -forge_version=10.13.2.1286 -mod_version=2.3.2 \ No newline at end of file +mc_version=1.8 +forge_version=11.14.0.1290-1.8 +mcp_version=snapshot_nodoc_20150204 +mod_version=2.1.2 \ No newline at end of file From 4c8badf2c42f197781f11f46221fceca2079b9ef Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 10:23:01 +0100 Subject: [PATCH 002/109] Update import changes --- src/main/java/mapwriter/BlockColourGen.java | 1 - src/main/java/mapwriter/Mw.java | 16 +++++++---- src/main/java/mapwriter/MwUtil.java | 1 - .../java/mapwriter/forge/ClientProxy.java | 2 +- .../java/mapwriter/forge/EventHandler.java | 2 +- src/main/java/mapwriter/forge/MwForge.java | 27 +++++++++---------- .../java/mapwriter/forge/MwKeyHandler.java | 7 +++-- src/main/java/mapwriter/gui/MwGui.java | 5 ++-- .../mapwriter/gui/MwGuiDimensionDialog.java | 4 +-- .../java/mapwriter/gui/MwGuiMarkerDialog.java | 4 +-- .../mapwriter/gui/MwGuiTeleportDialog.java | 4 +-- .../java/mapwriter/overlay/OverlaySlime.java | 9 +++---- src/main/java/mapwriter/region/MwChunk.java | 7 +++-- 13 files changed, 44 insertions(+), 45 deletions(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index faac6118..cc054b23 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -5,7 +5,6 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.IIcon; import net.minecraft.world.biome.BiomeGenBase; // Static class to generate BlockColours. diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 11d41ad0..6f2b2eca 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -1,11 +1,21 @@ package mapwriter; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + import mapwriter.forge.MwConfig; import mapwriter.forge.MwForge; import mapwriter.forge.MwKeyHandler; import mapwriter.gui.MwGui; import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.map.*; +import mapwriter.map.MapTexture; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.map.MiniMap; +import mapwriter.map.Trail; +import mapwriter.map.UndergroundTexture; import mapwriter.overlay.OverlaySlime; import mapwriter.region.BlockColours; import mapwriter.region.RegionManager; @@ -18,10 +28,6 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - /* data transfers diff --git a/src/main/java/mapwriter/MwUtil.java b/src/main/java/mapwriter/MwUtil.java index b6d66f84..cbb03599 100644 --- a/src/main/java/mapwriter/MwUtil.java +++ b/src/main/java/mapwriter/MwUtil.java @@ -11,7 +11,6 @@ import mapwriter.forge.MwForge; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 2ffdb175..aadf680c 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -8,7 +8,7 @@ import mapwriter.overlay.OverlaySlime; import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.FMLCommonHandler; public class ClientProxy extends CommonProxy { diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 69e38c33..551ff10a 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -1,6 +1,5 @@ package mapwriter.forge; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; import mapwriter.Mw; import mapwriter.overlay.OverlaySlime; import net.minecraft.util.ChatComponentText; @@ -8,6 +7,7 @@ import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class EventHandler { diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index a4617b34..d51aa068 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -2,24 +2,23 @@ import java.net.InetSocketAddress; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import mapwriter.Mw; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.Mod.EventHandler; -import cpw.mods.fml.common.Mod.Instance; -import cpw.mods.fml.common.SidedProxy; -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import cpw.mods.fml.common.network.FMLNetworkEvent; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.Instance; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.common.network.FMLNetworkEvent; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; @Mod(modid="MapWriter", name="MapWriter", version="2.2.2") public class MwForge { diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index 32e3ca29..ed65c329 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -2,13 +2,12 @@ import mapwriter.Mw; import net.minecraft.client.settings.KeyBinding; +import net.minecraftforge.fml.client.registry.ClientRegistry; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.InputEvent; import org.lwjgl.input.Keyboard; -import cpw.mods.fml.client.registry.ClientRegistry; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.InputEvent; - public class MwKeyHandler { public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index c7afe9e5..926e3370 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -16,13 +16,12 @@ import mapwriter.tasks.RebuildRegionsTask; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - @SideOnly(Side.CLIENT) public class MwGui extends GuiScreen { private Mw mw; diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java index 18d8c84f..6fca1941 100644 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -3,8 +3,8 @@ import mapwriter.Mw; import mapwriter.map.MapView; import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MwGuiDimensionDialog extends MwGuiTextDialog { diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java index 2e571158..27eb6102 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -3,8 +3,8 @@ import mapwriter.map.Marker; import mapwriter.map.MarkerManager; import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MwGuiMarkerDialog extends MwGuiTextDialog { diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index 77e965e6..8ad24534 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -3,8 +3,8 @@ import mapwriter.Mw; import mapwriter.map.MapView; import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MwGuiTeleportDialog extends MwGuiTextDialog { diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java index 5233a0df..e5dabfd8 100644 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -1,17 +1,16 @@ package mapwriter.overlay; +import java.awt.Point; +import java.util.ArrayList; +import java.util.Random; + import mapwriter.api.IMwChunkOverlay; import mapwriter.api.IMwDataProvider; import mapwriter.map.MapView; import mapwriter.map.mapmode.MapMode; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.MathHelper; -import java.awt.*; -import java.util.ArrayList; -import java.util.Random; - public class OverlaySlime implements IMwDataProvider { public static boolean seedFound = false; diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index f6c63782..457ce812 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -7,15 +7,14 @@ import java.util.Iterator; import java.util.Map; -import org.apache.logging.log4j.Level; - -import cpw.mods.fml.common.FMLLog; import net.minecraft.block.Block; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.ChunkPosition; +import net.minecraftforge.fml.common.FMLLog; + +import org.apache.logging.log4j.Level; public class MwChunk implements IChunk { public static final int SIZE = 16; From bb0da21cc56cb9d6546201f9ec491cba5dfeea55 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 12:31:20 +0100 Subject: [PATCH 003/109] 1.8 error fixes --- .../.launches/Client.launch | 14 --- src/main/java/mapwriter/BlockColourGen.java | 27 +++-- src/main/java/mapwriter/ChunkManager.java | 17 +-- src/main/java/mapwriter/Mw.java | 11 +- src/main/java/mapwriter/MwUtil.java | 3 +- src/main/java/mapwriter/Render.java | 94 +++++++++------- .../java/mapwriter/forge/ClientProxy.java | 3 +- src/main/java/mapwriter/forge/MwForge.java | 9 +- .../java/mapwriter/forge/MwKeyHandler.java | 21 ++-- src/main/java/mapwriter/gui/MwGui.java | 14 ++- .../java/mapwriter/gui/MwGuiOptionSlot.java | 3 +- src/main/java/mapwriter/gui/MwGuiOptions.java | 18 ++- .../java/mapwriter/gui/MwGuiTextDialog.java | 6 +- .../mapwriter/map/UndergroundTexture.java | 7 +- .../java/mapwriter/overlay/OverlaySlime.java | 5 +- .../java/mapwriter/region/ChunkRender.java | 9 +- src/main/java/mapwriter/region/MwChunk.java | 106 ++++++++++++------ 17 files changed, 210 insertions(+), 157 deletions(-) delete mode 100644 eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Client.launch diff --git a/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Client.launch b/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Client.launch deleted file mode 100644 index e9115feb..00000000 --- a/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Client.launch +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index cc054b23..92d0f76e 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -4,7 +4,9 @@ import mapwriter.region.BlockColours.BlockType; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.util.BlockPos; import net.minecraft.world.biome.BiomeGenBase; // Static class to generate BlockColours. @@ -15,7 +17,7 @@ public class BlockColourGen { - private static int getIconMapColour(IIcon icon, Texture terrainTexture) { + private static int getIconMapColour(TextureAtlasSprite icon, Texture terrainTexture) { // flipped icons have the U and V coords reversed (minU > maxU, minV > maxV). // thanks go to taelnia for fixing this. int iconX = (int) Math.round(((float) terrainTexture.w) * Math.min(icon.getMinU(), icon.getMaxU())); @@ -48,7 +50,7 @@ private static int adjustBlockColourFromType(BlockColours bc, int blockAndMeta, // fix crash when mods don't implement getRenderColor for all // block meta values. try { - int renderColour = block.getRenderColor(blockAndMeta & 0xf); + int renderColour = block.getRenderColor(block.getStateFromMeta(blockAndMeta & 0xf)); if (renderColour != 0xffffff) { blockColour = Render.multiplyColours(blockColour, 0xff000000 | renderColour); } @@ -74,8 +76,8 @@ private static void genBiomeColours(BlockColours bc) { for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { if (BiomeGenBase.getBiomeGenArray()[i] != null) { bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); - bc.setBiomeGrassShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeGrassColor(0,0,0) & 0xffffff); //FIXME 0,0,0? - bc.setBiomeFoliageShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeFoliageColor(0,0,0) & 0xffffff); //FIXME 0,0,0? + bc.setBiomeGrassShading(i, BiomeGenBase.getBiomeGenArray()[i].getGrassColorAtPos(new BlockPos(0, 0, 0)) & 0xffffff); //FIXME 0,0,0? + bc.setBiomeFoliageShading(i, BiomeGenBase.getBiomeGenArray()[i].getFoliageColorAtPos(new BlockPos(0, 0, 0)) & 0xffffff); //FIXME 0,0,0? } else { bc.setBiomeWaterShading(i, 0xffffff); bc.setBiomeGrassShading(i, 0xffffff); @@ -116,7 +118,7 @@ public static void genBlockColours(BlockColours bc) { //for (int blockID = 0; blockID < 4096; blockID++) { //TODO: replace hardcoded 4096 with actual registry size for (Object oblock : Block.blockRegistry){ Block block = (Block)oblock; - int blockID = block.getIdFromBlock(block); + int blockID = Block.getIdFromBlock(block); for (int dv = 0; dv < 17; dv++) { @@ -125,9 +127,9 @@ public static void genBlockColours(BlockColours bc) { if (block != null) { - IIcon icon = null; + TextureAtlasSprite icon = null; try { - icon = block.getIcon(1, dv); + icon = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(block.getStateFromMeta(dv)); } catch (Exception e) { //MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", blockID, dv); //e.printStackTrace(); @@ -148,11 +150,12 @@ public static void genBlockColours(BlockColours bc) { //request icon with meta 16, carpenterblocks uses this method to get the real texture //this makes the carpenterblocks render as brown blocks on the map - if (blockColour == 0) - { - icon = block.getIcon(1, 16); - blockColour = getIconMapColour(icon, terrainTexture); - } + //FIXME:check how carpenterblocks fixes this + //if (blockColour == 0) + //{ + // icon = block.getIcon(1, 16); + // blockColour = getIconMapColour(icon, terrainTexture); + //} u1Last = u1; u2Last = u2; v1Last = v1; diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index ef4296d3..e534fd93 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -32,29 +32,24 @@ public synchronized void close() { // only MwChunk's should be used in the background thread. // make this a full copy of chunk data to prevent possible race conditions <-- done public static MwChunk copyToMwChunk(Chunk chunk) { - - byte[][] msbArray = new byte[16][]; - byte[][] lsbArray = new byte[16][]; - byte[][] metaArray = new byte[16][]; byte[][] lightingArray = new byte[16][]; Map TileEntityMap = new HashMap(); - TileEntityMap.putAll(chunk.chunkTileEntityMap); + TileEntityMap.putAll(chunk.getTileEntityMap()); + char[][] dataArray = new char[16][]; ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); if (storageArrays != null) { for (ExtendedBlockStorage storage : storageArrays) { if (storage != null) { int y = (storage.getYLocation() >> 4) & 0xf; - lsbArray[y] = Arrays.copyOf(storage.getBlockLSBArray(), storage.getBlockLSBArray().length); - msbArray[y] = (storage.getBlockMSBArray() != null) ? Arrays.copyOf(storage.getBlockMSBArray().data, storage.getBlockMSBArray().data.length) : null; - metaArray[y] = (storage.getMetadataArray() != null) ? Arrays.copyOf(storage.getMetadataArray().data, storage.getMetadataArray().data.length) : null; - lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().data, storage.getBlocklightArray().data.length) : null; + dataArray[y] = storage.getData(); + lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; } } } - return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.worldObj.provider.dimensionId, - msbArray, lsbArray, metaArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); + return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), + dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); } public synchronized void addChunk(Chunk chunk) { diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 6f2b2eca..f206d7d7 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -162,7 +162,6 @@ public class Mw { public Mw(MwConfig config) { // client only initialization - // oops, no idea why I was using a ModLoader method to get the Minecraft instance before this.mc = Minecraft.getMinecraft(); // load config @@ -177,6 +176,8 @@ public Mw(MwConfig config) { RegionManager.logger = MwForge.logger; instance = this; + + this.loadConfig(); } public String getWorldName() { @@ -468,8 +469,6 @@ public void load() { IntegratedServer server = this.mc.getIntegratedServer(); this.multiplayer = (server == null); - this.loadConfig(); - this.worldName = this.getWorldName(); // get world and image directories @@ -586,7 +585,7 @@ public void onWorldLoad(World world) { // world.getWorldInfo().getWorldName(), // world.provider.dimensionId); - this.playerDimension = world.provider.dimensionId; + this.playerDimension = world.provider.getDimensionId(); if (this.ready) { this.addDimension(this.playerDimension); this.miniMap.view.setDimension(this.playerDimension); @@ -651,7 +650,7 @@ public void onTick() { // add chunk to the set of loaded chunks public void onChunkLoad(Chunk chunk) { this.load(); - if ((chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { + if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { if (this.ready) { this.chunkManager.addChunk(chunk); } else { @@ -663,7 +662,7 @@ public void onChunkLoad(Chunk chunk) { // remove chunk from the set of loaded chunks. // convert to mwchunk and write chunk to region file if in multiplayer. public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { + if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { this.chunkManager.removeChunk(chunk); } } diff --git a/src/main/java/mapwriter/MwUtil.java b/src/main/java/mapwriter/MwUtil.java index cbb03599..ee93847b 100644 --- a/src/main/java/mapwriter/MwUtil.java +++ b/src/main/java/mapwriter/MwUtil.java @@ -11,6 +11,7 @@ import mapwriter.forge.MwForge; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; @@ -67,7 +68,7 @@ public static File getFreeFilename(File dir, String baseName, String ext) { } public static void printBoth(String msg) { - EntityClientPlayerMP thePlayer = Minecraft.getMinecraft().thePlayer; + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; if (thePlayer != null) { thePlayer.addChatMessage(new ChatComponentText(msg)); } diff --git a/src/main/java/mapwriter/Render.java b/src/main/java/mapwriter/Render.java index 433612a2..1070392b 100644 --- a/src/main/java/mapwriter/Render.java +++ b/src/main/java/mapwriter/Render.java @@ -3,6 +3,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -26,11 +27,14 @@ public static void setColourWithAlphaPercent(int colour, int alphaPercent) { } public static void setColour(int colour) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f( (float) ((colour >> 16) & 0xff) / 255.0f, (float) ((colour >> 8) & 0xff) / 255.0f, (float) ((colour) & 0xff) / 255.0f, (float) ((colour >> 24) & 0xff) / 255.0f); + GL11.glDisable(GL11.GL_BLEND); } public static void resetColour() { @@ -154,13 +158,15 @@ public static void drawTexturedRect(double x, double y, double w, double h, doub GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - tes.addVertexWithUV(x + w, y, zDepth, u2, v1); - tes.addVertexWithUV(x, y, zDepth, u1, v1); - tes.addVertexWithUV(x, y + h, zDepth, u1, v2); - tes.addVertexWithUV(x + w, y + h, zDepth, u2, v2); - tes.draw(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawingQuads(); + renderer.addVertexWithUV(x + w, y, zDepth, u2, v1); + renderer.addVertexWithUV(x, y, zDepth, u1, v1); + renderer.addVertexWithUV(x, y + h, zDepth, u1, v2); + renderer.addVertexWithUV(x + w, y + h, zDepth, u2, v2); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glDisable(GL11.GL_BLEND); } catch (NullPointerException e) { MwUtil.log("MwRender.drawTexturedRect: null pointer exception"); @@ -173,13 +179,15 @@ public static void drawArrow(double x, double y, double angle, double length) { GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_FAN); - tes.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); - tes.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); - tes.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); - tes.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); - tes.draw(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_FAN); + renderer.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); + renderer.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); + renderer.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); + renderer.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } @@ -188,12 +196,14 @@ public static void drawTriangle(double x1, double y1, double x2, double y2, doub GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLES); - tes.addVertex(x1, y1, zDepth); - tes.addVertex(x2, y2, zDepth); - tes.addVertex(x3, y3, zDepth); - tes.draw(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLES); + renderer.addVertex(x1, y1, zDepth); + renderer.addVertex(x2, y2, zDepth); + renderer.addVertex(x3, y3, zDepth); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } @@ -202,13 +212,15 @@ public static void drawRect(double x, double y, double w, double h) { GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - tes.addVertex(x + w, y, zDepth); - tes.addVertex(x, y, zDepth); - tes.addVertex(x, y + h, zDepth); - tes.addVertex(x + w, y + h, zDepth); - tes.draw(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawingQuads(); + renderer.addVertex(x + w, y, zDepth); + renderer.addVertex(x, y, zDepth); + renderer.addVertex(x, y + h, zDepth); + renderer.addVertex(x + w, y + h, zDepth); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } @@ -217,16 +229,18 @@ public static void drawCircle(double x, double y, double r) { GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_FAN); - tes.addVertex(x, y, zDepth); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_FAN); + renderer.addVertex(x, y, zDepth); // for some the circle is only drawn if theta is decreasing rather than ascending double end = Math.PI * 2.0; double incr = end / circleSteps; for (double theta = -incr; theta < end; theta += incr) { - tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); } - tes.draw(); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } @@ -235,17 +249,19 @@ public static void drawCircleBorder(double x, double y, double r, double width) GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_STRIP); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_STRIP); // for some the circle is only drawn if theta is decreasing rather than ascending double end = Math.PI * 2.0; double incr = end / circleSteps; double r2 = r + width; for (double theta = -incr; theta < end; theta += incr) { - tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - tes.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); + renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + renderer.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); } - tes.draw(); + //renderer.finishDrawing(); + tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } @@ -264,7 +280,7 @@ public static void drawRectBorder(double x, double y, double w, double h, double public static void drawString(int x, int y, int colour, String formatString, Object...args) { Minecraft mc = Minecraft.getMinecraft(); //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRenderer; + FontRenderer fr = mc.fontRendererObj; String s = String.format(formatString, args); fr.drawStringWithShadow(s, x, y, colour); } @@ -272,7 +288,7 @@ public static void drawString(int x, int y, int colour, String formatString, Obj public static void drawCentredString(int x, int y, int colour, String formatString, Object...args) { Minecraft mc = Minecraft.getMinecraft(); //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRenderer; + FontRenderer fr = mc.fontRendererObj; String s = String.format(formatString, args); int w = fr.getStringWidth(s); fr.drawStringWithShadow(s, x - (w / 2), y, colour); diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index aadf680c..b945ec4d 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -6,7 +6,6 @@ import mapwriter.api.MwAPI; import mapwriter.overlay.OverlayGrid; import mapwriter.overlay.OverlaySlime; -import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.FMLCommonHandler; @@ -25,7 +24,7 @@ public void load() { // temporary workaround for user defined key bindings not being loaded // at game start. see https://github.com/MinecraftForge/FML/issues/378 // for more info. - Minecraft.getMinecraft().gameSettings.loadOptions(); + //Minecraft.getMinecraft().gameSettings.loadOptions(); } public void postInit() { diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index d51aa068..100d5442 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -2,12 +2,16 @@ import java.net.InetSocketAddress; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import mapwriter.Mw; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; @@ -17,9 +21,6 @@ import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - @Mod(modid="MapWriter", name="MapWriter", version="2.2.2") public class MwForge { @@ -58,7 +59,7 @@ public void renderMap(RenderGameOverlayEvent.Post event){ @SubscribeEvent public void onConnected(FMLNetworkEvent.ClientConnectedToServerEvent event){ if (!event.isLocal) { - InetSocketAddress address = (InetSocketAddress) event.manager.getSocketAddress(); + InetSocketAddress address = (InetSocketAddress) event.manager.getRemoteAddress(); Mw.instance.setServerDetails(address.getHostName(), address.getPort()); } } diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index ed65c329..bd6be920 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -2,12 +2,13 @@ import mapwriter.Mw; import net.minecraft.client.settings.KeyBinding; + +import org.lwjgl.input.Keyboard; + import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; -import org.lwjgl.input.Keyboard; - public class MwKeyHandler { public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); @@ -33,35 +34,35 @@ public MwKeyHandler(){ @SubscribeEvent public void onKeyPress(InputEvent.KeyInputEvent event){ - if(keyMapGui.getIsKeyPressed()){ + if(keyMapGui.isPressed()){ KeyBinding.setKeyBindState(keyMapGui.getKeyCode(), false); Mw.instance.onKeyDown(keyMapGui); } - if(keyNewMarker.getIsKeyPressed()){ + if(keyNewMarker.isPressed()){ KeyBinding.setKeyBindState(keyNewMarker.getKeyCode(), false); Mw.instance.onKeyDown(keyNewMarker); } - if(keyMapMode.getIsKeyPressed()){ + if(keyMapMode.isPressed()){ KeyBinding.setKeyBindState(keyMapMode.getKeyCode(), false); Mw.instance.onKeyDown(keyMapMode); } - if(keyNextGroup.getIsKeyPressed()){ + if(keyNextGroup.isPressed()){ KeyBinding.setKeyBindState(keyNextGroup.getKeyCode(), false); Mw.instance.onKeyDown(keyNextGroup); } - if(keyTeleport.getIsKeyPressed()){ + if(keyTeleport.isPressed()){ KeyBinding.setKeyBindState(keyTeleport.getKeyCode(), false); Mw.instance.onKeyDown(keyTeleport); } - if(keyZoomIn.getIsKeyPressed()){ + if(keyZoomIn.isPressed()){ KeyBinding.setKeyBindState(keyZoomIn.getKeyCode(), false); Mw.instance.onKeyDown(keyZoomIn); } - if(keyZoomOut.getIsKeyPressed()){ + if(keyZoomOut.isPressed()){ KeyBinding.setKeyBindState(keyZoomOut.getKeyCode(), false); Mw.instance.onKeyDown(keyZoomOut); } - if(keyUndergroundMode.getIsKeyPressed()){ + if(keyUndergroundMode.isPressed()){ KeyBinding.setKeyBindState(keyUndergroundMode.getKeyCode(), false); Mw.instance.onKeyDown(keyUndergroundMode); } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 926e3370..2ce4f3de 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,6 +1,7 @@ package mapwriter.gui; import java.awt.Point; +import java.io.IOException; import mapwriter.Mw; import mapwriter.MwUtil; @@ -16,6 +17,7 @@ import mapwriter.tasks.RebuildRegionsTask; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.BlockPos; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -140,9 +142,9 @@ public Marker getMarkerNearScreenPos(int x, int y) { public int getHeightAtBlockPos(int bX, int bZ) { int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.dimensionId; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getChunkFromBlockCoords(bX, bZ).getHeightValue(bX & 0xf, bZ & 0xf); + bY = this.mw.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).getHeight(bX & 0xf, bZ & 0xf); } return bY; } @@ -306,7 +308,7 @@ protected void keyTyped(char c, int key) { // override GuiScreen's handleMouseInput to process // the scroll wheel. @Override - public void handleMouseInput() { + public void handleMouseInput() throws IOException { if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) return; @@ -488,8 +490,8 @@ public void drawStatus(int bX, int bY, int bZ) { s = String.format("cursor: (%d, ?, %d)", bX, bZ); } if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(bX, bZ).isEmpty()) { - s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(bX, bZ).biomeName); + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { + s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); } } @@ -604,7 +606,7 @@ public void drawScreen(int mouseX, int mouseY, float f) { // draw name of player under mouse cursor if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayName(), + this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); diff --git a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java index a1e35a57..0cf293ee 100644 --- a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java +++ b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java @@ -5,7 +5,6 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSlot; -import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; public class MwGuiOptionSlot extends GuiSlot { @@ -223,7 +222,7 @@ protected void drawBackground() { } @Override - protected void drawSlot(int i, int x, int y, int i4, Tessellator tessellator, int i5, int i6){ + protected void drawSlot(int i, int x, int y, int i4, int i5, int i6){ GuiButton button = buttons[i]; button.xPosition = x; button.yPosition = y; diff --git a/src/main/java/mapwriter/gui/MwGuiOptions.java b/src/main/java/mapwriter/gui/MwGuiOptions.java index 52709fab..ad02dd0f 100644 --- a/src/main/java/mapwriter/gui/MwGuiOptions.java +++ b/src/main/java/mapwriter/gui/MwGuiOptions.java @@ -1,5 +1,7 @@ package mapwriter.gui; +import java.io.IOException; + import mapwriter.Mw; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; @@ -38,12 +40,22 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.drawCenteredString(this.fontRendererObj, "MapWriter Options", this.width / 2, 10, 0xffffff); super.drawScreen(mouseX, mouseY, f); } + + public void handleMouseInput() throws IOException + { + if (this.optionSlot != null) + { + this.optionSlot.handleMouseInput(); + } + super.handleMouseInput(); + } - protected void mouseClicked(int x, int y, int button) { - super.mouseClicked(x, y, button); + protected void mouseClicked(int x, int y, int button) throws IOException { + super.mouseClicked(x, y, button); } + - protected void keyTyped(char c, int k) { + protected void keyTyped(char c, int k) throws IOException { if (this.optionSlot.keyTyped(c, k)) { super.keyTyped(c, k); } diff --git a/src/main/java/mapwriter/gui/MwGuiTextDialog.java b/src/main/java/mapwriter/gui/MwGuiTextDialog.java index 42e7c73c..a4788552 100644 --- a/src/main/java/mapwriter/gui/MwGuiTextDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTextDialog.java @@ -1,5 +1,7 @@ package mapwriter.gui; +import java.io.IOException; + import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; @@ -33,7 +35,7 @@ private void newTextField() { this.text = this.textField.getText(); } int w = this.width * textDialogWidthPercent / 100; - this.textField = new GuiTextField(this.fontRendererObj, + this.textField = new GuiTextField(0,this.fontRendererObj, (this.width - w) / 2 + 5, textDialogY, w - 10, @@ -127,7 +129,7 @@ public void drawScreen(int mouseX, int mouseY, float f) { super.drawScreen(mouseX, mouseY, f); } - protected void mouseClicked(int x, int y, int button) { + protected void mouseClicked(int x, int y, int button) throws IOException { super.mouseClicked(x, y, button); } diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java index f8d603bb..07199725 100644 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -9,6 +9,7 @@ import mapwriter.region.IChunk; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.util.BlockPos; import net.minecraft.world.chunk.Chunk; import org.lwjgl.opengl.GL11; @@ -44,7 +45,7 @@ public int getMaxY() { public int getBlockAndMetadata(int x, int y, int z) { Block block = this.chunk.getBlock(x, y, z); int blockid = Block.blockRegistry.getIDForObject(block); - int meta = this.chunk.getBlockMetadata(x, y, z); + int meta = this.chunk.getBlockMetadata(new BlockPos(x, y, z)); return ((blockid & 0xfff) << 4) | (meta & 0xf); } @@ -55,7 +56,7 @@ public int getBiome(int x, int z) { @Override public int getLightValue(int x, int y, int z) { - return this.chunk.getBlockLightValue(x, y, z, 0); + return this.chunk.getBlock(new BlockPos(x,y,z)).getLightValue(); } } @@ -200,7 +201,7 @@ private void processBlock(int xi, int y, int zi) { if (columnFlag == ChunkRender.FLAG_UNPROCESSED) { // if column not yet processed WorldClient world = this.mw.mc.theWorld; - Block block = world.getBlock(x, y, z); + Block block = world.getBlockState(new BlockPos(x,y,z)).getBlock(); if ((block == null) || !block.isOpaqueCube()) { // if block is not opaque this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_NON_OPAQUE; diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java index e5dabfd8..778843d2 100644 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -9,6 +9,7 @@ import mapwriter.map.MapView; import mapwriter.map.mapmode.MapMode; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.MathHelper; public class OverlaySlime implements IMwDataProvider { @@ -23,7 +24,7 @@ public static void setSeed(long seed){ } public static void askSeed(){ - EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; if(player == null) return; player.sendChatMessage("/seed"); //Send the /seed command to the server seedAsked = true; @@ -69,7 +70,7 @@ public ArrayList getChunksOverlay(int dim, double centerX, doub // We should pass the center of the map too to reduce the display like in this case // and the zoom lvl, to provide higher level informations - if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.dimensionId != dim) + if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.getDimensionId() != dim) return new ArrayList(); int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 6dc79341..809ce586 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -77,7 +77,8 @@ public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, i double b = 0.0; for (; y > 0; y--) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - + int block = blockAndMeta >> 4; + int meta = (blockAndMeta | 0xfff0) ^ 0xfff0; int c1 = bc.getColour(blockAndMeta); int alpha = (c1 >> 24) & 0xff; // no need to process block if it is transparent @@ -102,8 +103,8 @@ public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, i b = b + (a * c1A * c1B * c2B); a = a * (1.0 - c1A); } - // break when an opaque block is encountered - if (alpha == 0xff) { + //break when an opaque block is encountered + if (alpha == 255) { break; } } @@ -161,7 +162,7 @@ public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, in } } } else { - y = chunkMaxY; + y = chunkMaxY-1; } int pixelOffset = offset + (z * scanSize) + x; diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 457ce812..ba4c27e3 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -12,6 +12,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.NibbleArray; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; @@ -23,9 +25,7 @@ public class MwChunk implements IChunk { public final int z; public final int dimension; - public final byte[][] msbArray; - public final byte[][] lsbArray; - public final byte[][] metaArray; + char[][] dataArray = new char[16][]; public final byte[][] lightingArray; public final Map tileentityMap; @@ -33,19 +33,17 @@ public class MwChunk implements IChunk { public final int maxY; - public MwChunk(int x, int z, int dimension, byte[][] msbArray, byte[][] lsbArray, byte[][] metaArray, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { + public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { this.x = x; this.z = z; this.dimension = dimension; - this.msbArray = msbArray; - this.lsbArray = lsbArray; - this.metaArray = metaArray; this.biomeArray = biomeArray; this.lightingArray = lightingArray; this.tileentityMap = TileEntityMap; + this.dataArray = data; int maxY = 0; for (int y = 0; y < 16; y++) { - if (lsbArray[y] != null) { + if (data[y] != null) { maxY = (y << 4) + 15; } } @@ -60,9 +58,8 @@ public String toString() { public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { byte[] biomeArray = null; - byte[][] msbArray = new byte[16][]; byte[][] lsbArray = new byte[16][]; - byte[][] metaArray = new byte[16][]; + char[][] data = new char[16][]; byte[][] lightingArray = new byte[16][]; Map TileEntityMap = new HashMap(); @@ -121,11 +118,19 @@ public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFi NBTTagCompound section = sections.getCompoundTagAt(k); int y = section.getByte("Y"); lsbArray[y & 0xf] = section.getByteArray("Blocks"); - if (section.hasKey("Add", 7)) + NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); + NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; + + data[y & 0xf] = new char[lsbArray[y].length]; + + for (int l = 0; l < data[y & 0xf].length; ++l) { - msbArray[y & 0xf] = section.getByteArray("Add"); + int i1 = l & 15; + int j1 = l >> 8 & 15; + int k1 = l >> 4 & 15; + int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; + data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); } - metaArray[y & 0xf] = section.getByteArray("Data"); } biomeArray = level.getByteArray("Biomes"); @@ -140,9 +145,7 @@ public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFi TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); if (tileentity != null) { - ChunkPosition chunkposition = new ChunkPosition(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord); - - TileEntityMap.put(chunkposition, tileentity); + TileEntityMap.put(tileentity.getPos(), tileentity); } } } @@ -161,7 +164,7 @@ public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFi //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); } - return new MwChunk(x, z, dimension, msbArray, lsbArray, metaArray, lightingArray, biomeArray,TileEntityMap); + return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); } public boolean isEmpty() { @@ -189,17 +192,21 @@ public int getMaxY() { public int getBlockAndMetadata(int x, int y, int z) { int yi = (y >> 4) & 0xf; int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - ChunkPosition chunkposition = new ChunkPosition(x, y, z); - int lsb = ((this.lsbArray != null) && (this.lsbArray[yi] != null)&& (this.lsbArray[yi].length != 0)) ? this.lsbArray[yi][offset] : 0; - int msb = ((this.msbArray != null) && (this.msbArray[yi] != null) && (this.msbArray[yi].length != 0)) ? this.msbArray[yi][offset >> 1] : 0; - int meta = ((this.metaArray != null) && (this.metaArray[yi] != null)&& (this.metaArray[yi].length != 0)) ? this.metaArray[yi][offset >> 1] : 0; + + int lsb = 0; + int msb = 0; + int meta = 0; + + BlockPos pos = new BlockPos(x,y,z); + + char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; //check if the block has a tileentity if so use the blockdata in the tileentity //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) - - if (this.tileentityMap.containsKey(chunkposition)) + if (this.tileentityMap.containsKey(pos)) { - TileEntity value = (TileEntity)this.tileentityMap.get(chunkposition); + + TileEntity value = (TileEntity)this.tileentityMap.get(pos); NBTTagCompound tag = new NBTTagCompound(); value.writeToNBT(tag); int id = 0; @@ -209,16 +216,19 @@ public int getBlockAndMetadata(int x, int y, int z) { String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); int end = material.indexOf("_"); + //block with metadata if (end != -1) { id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); lsb = (id & 255); + if (id > 255){msb = (id & 3840) >> 8;} else {msb = 0;} meta = Integer.parseInt(material.substring(end+1)); } + //block without metadata else { id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); @@ -226,9 +236,8 @@ public int getBlockAndMetadata(int x, int y, int z) { lsb = (id & 255); if (id > 255){msb = (id & 3840) >> 8;} else {msb = 0;} - - meta = 0; } + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); } else if (tag.getString("id") =="TileEntityCarpentersBlock") { @@ -247,13 +256,15 @@ else if (tag.getString("id") =="TileEntityCarpentersBlock") { meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); } + + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); } } } //return ((offset & 1) == 1) ? // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : - return ((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f); + return (int)data; } //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data @@ -263,7 +274,6 @@ private NBTTagCompound writeChunkToNBT() NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound.setTag("Level", nbttagcompound1); - nbttagcompound1.setByte("V", (byte)1); nbttagcompound1.setInteger("xPos", this.x); nbttagcompound1.setInteger("zPos", this.z); @@ -272,23 +282,47 @@ private NBTTagCompound writeChunkToNBT() int i = 16; NBTTagCompound nbttagcompound2; - for (int y = 0; y < i; ++y) - { - if ((this.lsbArray != null) && (this.lsbArray[y] != null)) + for (int y = 0; y < this.dataArray.length; y++) + { + + byte[] abyte = new byte[this.dataArray[y].length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < this.dataArray[y].length; ++k) { + char c0 = this.dataArray[y][k]; + int l = k & 15; + int i1 = k >> 8 & 15; + int j1 = k >> 4 & 15; + + if (c0 >> 12 != 0) + { + if (nibblearray1 == null) + { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte)(c0 >> 4 & 255); + nibblearray.set(l, i1, j1, c0 & 15); + } + + nbttagcompound2 = new NBTTagCompound(); nbttagcompound2.setByte("Y", (byte)y); - nbttagcompound2.setByteArray("Blocks", this.lsbArray[y]); + nbttagcompound2.setByteArray("Blocks", abyte); - if ((this.msbArray != null) && (this.msbArray[y] != null)) + if (nibblearray1 != null) { - nbttagcompound2.setByteArray("Add", this.msbArray[y]); + nbttagcompound2.setByteArray("Add", nibblearray1.getData()); } - nbttagcompound2.setByteArray("Data", this.metaArray[y]); + nbttagcompound2.setByteArray("Data", nibblearray.getData()); nbttaglist.appendTag(nbttagcompound2); } - } nbttagcompound1.setTag("Sections", nbttaglist); nbttagcompound1.setByteArray("Biomes", this.biomeArray); From 1dae4b39c82f22a47e4f7788250b35f69cbe1d90 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 13:28:47 +0100 Subject: [PATCH 004/109] updated gitignore --- .gitignore | 12 +++++------- .../org.eclipse.debug.core/.launches/Server.launch | 13 ------------- 2 files changed, 5 insertions(+), 20 deletions(-) delete mode 100644 eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Server.launch diff --git a/.gitignore b/.gitignore index 102fb408..a9af55bb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,11 +10,9 @@ runtime .project .settings bin -/Build.bat -/Clean.bat -/Deploy.bat -/FixDependicies.bat -/Install Forge.bat -.nb-gradle -.nb-gradle-properties +Build.bat +Clean.bat +Deploy.bat +FixDependicies.bat +Install Forge.bat eclipse diff --git a/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Server.launch b/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Server.launch deleted file mode 100644 index 350eeffb..00000000 --- a/eclipse/.metadata/.plugins/org.eclipse.debug.core/.launches/Server.launch +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - From 6a8d199c520b00eabf704e6f6af79a6c0c178dc2 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 14:15:31 +0100 Subject: [PATCH 005/109] remove eclipse folder --- .../.projects/Minecraft/.location | Bin 133 -> 0 bytes .../launchConfigurationHistory.xml | 25 ------------------ 2 files changed, 25 deletions(-) delete mode 100644 eclipse/.metadata/.plugins/org.eclipse.core.resources/.projects/Minecraft/.location delete mode 100644 eclipse/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml diff --git a/eclipse/.metadata/.plugins/org.eclipse.core.resources/.projects/Minecraft/.location b/eclipse/.metadata/.plugins/org.eclipse.core.resources/.projects/Minecraft/.location deleted file mode 100644 index 3e7ec70b47733f7d607acfc0928dfa9ea8101c41..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 133 zcmZ?R*xjhShe1S2b=vdAllRFngoXxr>g%Uv=A>HbJ6q|87N-^!>xZQ#mlWma>AMu= z7bN9Z==)~or6w08rj@{1szwIB`6(%xdFlGTi3R0FnI)-3`nhlx0}410@%uB_(!kF> J)w|1&0RT_$E+hZ| diff --git a/eclipse/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml b/eclipse/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml deleted file mode 100644 index 1208f602..00000000 --- a/eclipse/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - From ab01031c3aeadcb6ebd88f20372e28c06a3bd7c1 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 14:37:40 +0100 Subject: [PATCH 006/109] Fixed version (minecraft 1.8 -> 2.2.3) --- build.properties | 2 +- src/main/java/mapwriter/forge/MwForge.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.properties b/build.properties index 0c869281..6ccb45c4 100644 --- a/build.properties +++ b/build.properties @@ -1,4 +1,4 @@ mc_version=1.8 forge_version=11.14.0.1290-1.8 mcp_version=snapshot_nodoc_20150204 -mod_version=2.1.2 \ No newline at end of file +mod_version=2.2.3 \ No newline at end of file diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index 100d5442..22acb49e 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -21,7 +21,7 @@ import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; -@Mod(modid="MapWriter", name="MapWriter", version="2.2.2") +@Mod(modid="MapWriter", name="MapWriter", version="2.2.3") public class MwForge { @Instance("MapWriter") From 7bdc795039a03ce9ffcb42b598d70c3267f55156 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 16:36:13 +0100 Subject: [PATCH 007/109] should fix a race condition --- src/main/java/mapwriter/region/MwChunk.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index ba4c27e3..d71d0fcb 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -283,8 +283,9 @@ private NBTTagCompound writeChunkToNBT() NBTTagCompound nbttagcompound2; for (int y = 0; y < this.dataArray.length; y++) - { - + { + if (this.dataArray[y] != null) + { byte[] abyte = new byte[this.dataArray[y].length]; NibbleArray nibblearray = new NibbleArray(); NibbleArray nibblearray1 = null; @@ -325,6 +326,7 @@ private NBTTagCompound writeChunkToNBT() } nbttagcompound1.setTag("Sections", nbttaglist); + } nbttagcompound1.setByteArray("Biomes", this.biomeArray); NBTTagList nbttaglist2 = new NBTTagList(); From 0e6bf208fd81e174660b18d3964f238e2a1d9f1a Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 4 Feb 2015 16:38:16 +0100 Subject: [PATCH 008/109] meta only goes to 16. --- src/main/java/mapwriter/BlockColourGen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 92d0f76e..8e621fac 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -120,7 +120,7 @@ public static void genBlockColours(BlockColours bc) { Block block = (Block)oblock; int blockID = Block.getIdFromBlock(block); - for (int dv = 0; dv < 17; dv++) { + for (int dv = 0; dv < 16; dv++) { int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); int blockColour = 0; From b95821b47c5b2998b7f80e57cd4aea366fb63cf6 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 5 Feb 2015 09:15:20 +0100 Subject: [PATCH 009/109] fix for the purple rendering of transparent blocks with no texture --- src/main/java/mapwriter/region/ChunkRender.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 809ce586..0a3476de 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -81,6 +81,13 @@ public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, i int meta = (blockAndMeta | 0xfff0) ^ 0xfff0; int c1 = bc.getColour(blockAndMeta); int alpha = (c1 >> 24) & 0xff; + + //this is the color that gets returned for air, so set aplha to 0 so the game continues to the next block in the colum + if (c1 == -8650628) + { + alpha = 0; + } + // no need to process block if it is transparent if (alpha > 0) { int biome = chunk.getBiome(x, z); From 580f700e02857baea43bbd53f8541306165dd873 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 5 Feb 2015 11:24:34 +0100 Subject: [PATCH 010/109] using the forge event to detect if the player died. --- src/main/java/mapwriter/Mw.java | 17 ++-- .../java/mapwriter/forge/EventHandler.java | 97 +++++++++++-------- 2 files changed, 68 insertions(+), 46 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index f206d7d7..31cdd8f9 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -23,6 +23,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.settings.KeyBinding; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; @@ -611,12 +612,13 @@ public void onTick() { // check if the game over screen is being displayed and if so // (thanks to Chrixian for this method of checking when the player is dead) - if (this.mc.currentScreen instanceof GuiGameOver) { - if (!this.onPlayerDeathAlreadyFired) { - this.onPlayerDeath(); - this.onPlayerDeathAlreadyFired = true; - } - } else if (!(this.mc.currentScreen instanceof MwGui)) { + //if (this.mc.currentScreen instanceof GuiGameOver) { + // if (!this.onPlayerDeathAlreadyFired) { + // this.onPlayerDeath(); + // this.onPlayerDeathAlreadyFired = true; + // } + //} + if (!(this.mc.currentScreen instanceof MwGui)) { // if the player is not dead this.onPlayerDeathAlreadyFired = false; // if in game (no gui screen) center the minimap on the player and render it. @@ -669,7 +671,7 @@ public void onChunkUnload(Chunk chunk) { // from onTick when mc.currentScreen is an instance of GuiGameOver // it's the only option to detect death client side - public void onPlayerDeath() { + public void onPlayerDeath(EntityPlayerMP player) { if (this.ready && (this.maxDeathMarkers > 0)) { this.updatePlayer(); int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - this.maxDeathMarkers + 1; @@ -679,6 +681,7 @@ public void onPlayerDeath() { // earliest death marker added. this.markerManager.delMarker(null, "playerDeaths"); } + this.markerManager.addMarker(MwUtil.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); this.markerManager.setVisibleGroupName("playerDeaths"); this.markerManager.update(); diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 551ff10a..34c48c46 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -2,69 +2,88 @@ import mapwriter.Mw; import mapwriter.overlay.OverlaySlime; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.DamageSource; import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class EventHandler { - + Mw mw; - + public EventHandler(Mw mw) { this.mw = mw; } - + @SubscribeEvent - public void eventChunkLoad(ChunkEvent.Load event){ - if(event.world.isRemote){ + public void eventChunkLoad(ChunkEvent.Load event) { + if (event.world.isRemote) { this.mw.onChunkLoad(event.getChunk()); } } - + @SubscribeEvent - public void eventChunkUnload(ChunkEvent.Unload event){ - if(event.world.isRemote){ + public void eventChunkUnload(ChunkEvent.Unload event) { + if (event.world.isRemote) { this.mw.onChunkUnload(event.getChunk()); } } - + @SubscribeEvent - public void eventWorldLoad(WorldEvent.Load event){ - if(event.world.isRemote){ + public void eventWorldLoad(WorldEvent.Load event) { + if (event.world.isRemote) { this.mw.onWorldLoad(event.world); } } - @SubscribeEvent - public void eventWorldUnload(WorldEvent.Unload event){ - if(event.world.isRemote){ - this.mw.onWorldUnload(event.world); - } - } + @SubscribeEvent + public void eventWorldUnload(WorldEvent.Unload event) { + if (event.world.isRemote) { + this.mw.onWorldUnload(event.world); + } + } + + @SubscribeEvent + public void onClientChat(ClientChatReceivedEvent event) { + if (OverlaySlime.seedFound || !OverlaySlime.seedAsked) + return; + try { // I don't want to crash the game when we derp up in here + if (event.message instanceof ChatComponentTranslation) { + ChatComponentTranslation component = (ChatComponentTranslation) event.message; + if (component.getKey().equals("commands.seed.success")) { + OverlaySlime.setSeed((Long) component.getFormatArgs()[0]); + event.setCanceled(true); // Don't let the player see this + // seed message, They didn't do + // /seed, we did + } + } else if (event.message instanceof ChatComponentText) { + ChatComponentText component = (ChatComponentText) event.message; + String msg = component.getUnformattedText(); + if (msg.startsWith("Seed: ")) { // Because bukkit... + OverlaySlime.setSeed(Long.parseLong(msg.substring(6))); + event.setCanceled(true); // Don't let the player see this + // seed message, They didn't do + // /seed, we did + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } - @SubscribeEvent - public void onClientChat(ClientChatReceivedEvent event){ - if(OverlaySlime.seedFound || !OverlaySlime.seedAsked) return; - try{ //I don't want to crash the game when we derp up in here - if(event.message instanceof ChatComponentTranslation){ - ChatComponentTranslation component = (ChatComponentTranslation) event.message; - if(component.getKey().equals("commands.seed.success")){ - OverlaySlime.setSeed((Long) component.getFormatArgs()[0]); - event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did - } - }else if(event.message instanceof ChatComponentText){ - ChatComponentText component = (ChatComponentText) event.message; - String msg = component.getUnformattedText(); - if(msg.startsWith("Seed: ")){ //Because bukkit... - OverlaySlime.setSeed(Long.parseLong(msg.substring(6))); - event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did - } - } - }catch(Exception e){ - //e.printStackTrace(); - } - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void eventPlayerDeath(LivingDeathEvent event) { + if (!event.isCanceled()) { + if (event.entityLiving.getEntityId() == net.minecraft.client.Minecraft + .getMinecraft().thePlayer.getEntityId()) { + this.mw.onPlayerDeath((EntityPlayerMP)event.entityLiving); + } + } + } } From c438d91f073f28e6b063271098bd49ff6d461afd Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 7 Feb 2015 00:01:20 +0100 Subject: [PATCH 011/109] Moved IO tasks (saving anvill file and rebuilding) to their own thread to free the other thread a bit --- src/main/java/mapwriter/BackgroundExecutor.java | 13 +++++++++++++ src/main/java/mapwriter/ChunkManager.java | 2 +- src/main/java/mapwriter/gui/MwGui.java | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index ebeb786b..4c8caf13 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -48,12 +48,14 @@ e.g. addTask(Task1) public class BackgroundExecutor { private ExecutorService executor; + private ExecutorService executor2; private LinkedList taskQueue; public boolean closed = false; public BackgroundExecutor() { this.executor = Executors.newSingleThreadExecutor(); this.taskQueue = new LinkedList(); + this.executor2 = Executors.newSingleThreadExecutor(); } // add a task to the queue @@ -68,6 +70,17 @@ public boolean addTask(Task task) { return this.closed; } + public boolean addTask2(Task task) { + if (!this.closed) { + Future future = this.executor2.submit(task); + task.setFuture(future); + this.taskQueue.add(task); + } else { + MwUtil.log("MwExecutor.addTask: error: cannot add task to closed executor"); + } + return this.closed; + } + // Pop a Task entry from the task queue and check if the task's thread has finished. // If it has completed then call onComplete for the task. // If it has not completed then push the task back on the queue. diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index e534fd93..2f511035 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -142,7 +142,7 @@ private void addSaveChunkTask(Chunk chunk) { if ((this.mw.multiplayer && this.mw.regionFileOutputEnabledMP) || (!this.mw.multiplayer && this.mw.regionFileOutputEnabledSP)) { if (!chunk.isEmpty()) { - this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); } } } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 2ce4f3de..48db82e1 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -184,7 +184,7 @@ public void regenerateView() { (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); this.mw.reloadBlockColours(); - this.mw.executor.addTask(new RebuildRegionsTask( + this.mw.executor.addTask2(new RebuildRegionsTask( this.mw, (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), From d5898f229d4aefc71aaecff421bbf1465ff94223 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 9 Feb 2015 16:45:25 +0100 Subject: [PATCH 012/109] -Worldload doesnt get triggered when traveling dimensions so change dimensions on player update. - odd thing with color for air blocks --- src/main/java/mapwriter/Mw.java | 9 +++++++-- src/main/java/mapwriter/region/ChunkRender.java | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 31cdd8f9..c2dca9fe 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -307,7 +307,12 @@ public void updatePlayer() { this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; // set by onWorldLoad - //this.playerDimension = this.mc.theWorld.provider.dimensionId; + this.playerDimension = this.mc.theWorld.provider.getDimensionId(); + if (this.miniMap.view.getDimension() != this.playerDimension) + { + this.addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); + } } public void addDimension(int dimension) { @@ -586,7 +591,7 @@ public void onWorldLoad(World world) { // world.getWorldInfo().getWorldName(), // world.provider.dimensionId); - this.playerDimension = world.provider.getDimensionId(); + //this.playerDimension = world.provider.getDimensionId(); if (this.ready) { this.addDimension(this.playerDimension); this.miniMap.view.setDimension(this.playerDimension); diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 0a3476de..e40afeef 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -164,6 +164,12 @@ public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, in for (y = 127; y >= 0; y--) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + + if (bc.getColour(blockAndMeta) == -8650628) + { + alpha = 0; + } + if (alpha != 0xff) { break; } @@ -199,6 +205,12 @@ public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels for (int y = startY; y < chunk.getMaxY(); y++) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + + if (bc.getColour(blockAndMeta) == -8650628) + { + alpha = 0; + } + if (alpha == 0xff) { break; } From 27a7e974b9c6f0b0b754b469bdf1696a2e9e6965 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 10:59:07 +0100 Subject: [PATCH 013/109] fix for the underground map rendered. getligh always returned 0 --- src/main/java/mapwriter/map/UndergroundTexture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java index 07199725..87a28bb4 100644 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -56,7 +56,7 @@ public int getBiome(int x, int z) { @Override public int getLightValue(int x, int y, int z) { - return this.chunk.getBlock(new BlockPos(x,y,z)).getLightValue(); + return this.chunk.getLightSubtracted(new BlockPos(x,y,z),0); } } From d8851778bc80a74cc49e098fec3256c5f1f585b8 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 11:20:34 +0100 Subject: [PATCH 014/109] no longer valid comments --- src/main/java/mapwriter/forge/ClientProxy.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index b945ec4d..1bb22a1b 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -21,16 +21,10 @@ public void load() { Mw mw = new Mw(this.config); MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); FMLCommonHandler.instance().bus().register(new MwKeyHandler()); - // temporary workaround for user defined key bindings not being loaded - // at game start. see https://github.com/MinecraftForge/FML/issues/378 - // for more info. - //Minecraft.getMinecraft().gameSettings.loadOptions(); } public void postInit() { MwAPI.registerDataProvider("Slime", new OverlaySlime()); MwAPI.registerDataProvider("Grid", new OverlayGrid()); - //MwAPI.registerDataProvider("Checker", new OverlayChecker()); - //MwAPI.setCurrentDataProvider("Slime"); } } From f66cd57d24bd9c904e765762948abbb60bfa28b2 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 11:30:28 +0100 Subject: [PATCH 015/109] Moved all forge events to the same file --- src/main/java/mapwriter/forge/EventHandler.java | 8 ++++++++ src/main/java/mapwriter/forge/MwForge.java | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 34c48c46..68bb5d1f 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -7,6 +7,7 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.DamageSource; import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; @@ -86,4 +87,11 @@ public void eventPlayerDeath(LivingDeathEvent event) { } } } + + @SubscribeEvent + public void renderMap(RenderGameOverlayEvent.Post event){ + if(event.type == RenderGameOverlayEvent.ElementType.ALL){ + Mw.instance.onTick(); + } + } } diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index 22acb49e..48c7e0d8 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -35,7 +35,6 @@ public class MwForge { @EventHandler public void preInit(FMLPreInitializationEvent event) { FMLCommonHandler.instance().bus().register(this); - MinecraftForge.EVENT_BUS.register(this); proxy.preInit(event.getSuggestedConfigurationFile()); } @@ -48,13 +47,6 @@ public void load(FMLInitializationEvent event) { public void postInit(FMLPostInitializationEvent event) { proxy.postInit(); } - - @SubscribeEvent - public void renderMap(RenderGameOverlayEvent.Post event){ - if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - Mw.instance.onTick(); - } - } @SubscribeEvent public void onConnected(FMLNetworkEvent.ClientConnectedToServerEvent event){ From c73375c39ce55b63634ef81c8452202cbdfa433d Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 14:37:20 +0100 Subject: [PATCH 016/109] removed unused code --- src/main/java/mapwriter/Mw.java | 30 +------------------ .../java/mapwriter/forge/EventHandler.java | 14 --------- 2 files changed, 1 insertion(+), 43 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index c2dca9fe..26a9ca85 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -585,26 +585,6 @@ public void close() { // Event handlers //////////////////////////////// - public void onWorldLoad(World world) { - //MwUtil.log("onWorldLoad: %s, name %s, dimension %d", - // world, - // world.getWorldInfo().getWorldName(), - // world.provider.dimensionId); - - //this.playerDimension = world.provider.getDimensionId(); - if (this.ready) { - this.addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); - } - } - - public void onWorldUnload(World world) { - //MwUtil.log("onWorldUnload: %s, name %s, dimension %d", - // world, - // world.getWorldInfo().getWorldName(), - // world.provider.dimensionId); - } - public void onTick() { this.load(); if (this.ready && (this.mc.thePlayer != null)) { @@ -614,15 +594,7 @@ public void onTick() { if (this.undergroundMode && ((this.tickCounter % 30) == 0)) { this.undergroundMapTexture.update(); } - - // check if the game over screen is being displayed and if so - // (thanks to Chrixian for this method of checking when the player is dead) - //if (this.mc.currentScreen instanceof GuiGameOver) { - // if (!this.onPlayerDeathAlreadyFired) { - // this.onPlayerDeath(); - // this.onPlayerDeathAlreadyFired = true; - // } - //} + if (!(this.mc.currentScreen instanceof MwGui)) { // if the player is not dead this.onPlayerDeathAlreadyFired = false; diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 68bb5d1f..8e2946c4 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -36,20 +36,6 @@ public void eventChunkUnload(ChunkEvent.Unload event) { } } - @SubscribeEvent - public void eventWorldLoad(WorldEvent.Load event) { - if (event.world.isRemote) { - this.mw.onWorldLoad(event.world); - } - } - - @SubscribeEvent - public void eventWorldUnload(WorldEvent.Unload event) { - if (event.world.isRemote) { - this.mw.onWorldUnload(event.world); - } - } - @SubscribeEvent public void onClientChat(ClientChatReceivedEvent event) { if (OverlaySlime.seedFound || !OverlaySlime.seedAsked) From 0f673fff61534da1abb59d6dcab7d5b6ebe19992 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 14:44:22 +0100 Subject: [PATCH 017/109] Removed more unused code --- src/main/java/mapwriter/Mw.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 26a9ca85..45338ea4 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -121,7 +121,6 @@ public class Mw { //public boolean lightingEnabled = false; // flags and counters - private boolean onPlayerDeathAlreadyFired = false; public boolean ready = false; public boolean multiplayer = false; public int tickCounter = 0; @@ -506,7 +505,6 @@ public void load() { } this.tickCounter = 0; - this.onPlayerDeathAlreadyFired = false; //this.multiplayer = !this.mc.isIntegratedServerRunning(); @@ -596,8 +594,6 @@ public void onTick() { } if (!(this.mc.currentScreen instanceof MwGui)) { - // if the player is not dead - this.onPlayerDeathAlreadyFired = false; // if in game (no gui screen) center the minimap on the player and render it. this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); this.miniMap.drawCurrentMap(); From dc412d943b253d4c1fdd226f46d1b28810f928be Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 15:06:39 +0100 Subject: [PATCH 018/109] updated to the latest forge build. fixed update error --- build.properties | 4 ++-- src/main/java/mapwriter/gui/MwGui.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build.properties b/build.properties index 6ccb45c4..6467f27e 100644 --- a/build.properties +++ b/build.properties @@ -1,4 +1,4 @@ mc_version=1.8 -forge_version=11.14.0.1290-1.8 -mcp_version=snapshot_nodoc_20150204 +forge_version=11.14.0.1295-1.8 +mcp_version=snapshot_nodoc_20150210 mod_version=2.2.3 \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 48db82e1..cc669138 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -144,7 +144,7 @@ public int getHeightAtBlockPos(int bX, int bZ) { int bY = 0; int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).getHeight(bX & 0xf, bZ & 0xf); + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); } return bY; } From 86bf1607f8feda5478f4d9c47d52b101968f5f22 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 10 Feb 2015 19:40:31 +0100 Subject: [PATCH 019/109] some more odd fixing build files --- build.gradle | 21 +++++++++++---------- build.properties | 4 +++- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 1ee26304..76432e12 100644 --- a/build.gradle +++ b/build.gradle @@ -16,15 +16,11 @@ buildscript { } apply plugin: 'forge' -apply plugin: 'maven' repositories { mavenLocal() } -group= "vectron" -archivesBaseName = "MapWriter" - // Define properties file ext.configFile = file "build.properties" @@ -35,10 +31,13 @@ configFile.withReader { project.ext.config = new ConfigSlurper().parse prop } +group= config.mod_group +archivesBaseName = config.mod_name + dependencies { } -version = "${project.config.mod_version}" +version = config.mod_version minecraft { version = config.mc_version + "-" + config.forge_version runDir = "eclipse" @@ -66,12 +65,15 @@ processResources from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' } +} version = "${project.minecraft.version}-${project.version}" + jar { -classifier = 'universal' +//classifier = 'universal' } + task sourceJar(type: Jar) { from sourceSets.main.java from new File(root, "dev") @@ -81,9 +83,8 @@ task sourceJar(type: Jar) { task devJar(type: Jar) { from sourceSets.main.output classifier = 'dev' - } +} - artifacts { +artifacts { archives sourceJar, devJar - } -} +} \ No newline at end of file diff --git a/build.properties b/build.properties index 6467f27e..a72fdb44 100644 --- a/build.properties +++ b/build.properties @@ -1,4 +1,6 @@ +mod_name=MapWriter +mod_group=vectron mc_version=1.8 forge_version=11.14.0.1295-1.8 mcp_version=snapshot_nodoc_20150210 -mod_version=2.2.3 \ No newline at end of file +mod_version=2.2.3 From c17eccc10bb98bda1b25d5293741874663eb96a1 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 12 Feb 2015 11:20:01 +0100 Subject: [PATCH 020/109] update to latest forge --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index a72fdb44..ea00e338 100644 --- a/build.properties +++ b/build.properties @@ -1,6 +1,6 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 -forge_version=11.14.0.1295-1.8 +forge_version=11.14.1.1309 mcp_version=snapshot_nodoc_20150210 mod_version=2.2.3 From ff90745c4a63d275b39269ee6fb8f9a4cbcf2b06 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 9 Mar 2015 09:37:48 +0100 Subject: [PATCH 021/109] updated to forge version 11.14.1.1334 --- .gitignore | 1 + build.properties | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index a9af55bb..0d14d550 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ Deploy.bat FixDependicies.bat Install Forge.bat eclipse +/Run.bat diff --git a/build.properties b/build.properties index ea00e338..32fb322d 100644 --- a/build.properties +++ b/build.properties @@ -1,6 +1,6 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 -forge_version=11.14.1.1309 -mcp_version=snapshot_nodoc_20150210 +forge_version=11.14.1.1334 +mcp_version=snapshot_20150309 mod_version=2.2.3 From e3efb63233366b86276062ee59cbf240ddec5559 Mon Sep 17 00:00:00 2001 From: blt Date: Fri, 27 Mar 2015 10:50:14 +0100 Subject: [PATCH 022/109] Changing the configuration to the new ingame config function fixed a bug when zooming on large map --- build.gradle | 32 ++- build.properties | 2 +- gradle/wrapper/gradle-wrapper.jar | Bin 50514 -> 51017 bytes gradle/wrapper/gradle-wrapper.properties | 4 +- gradlew.bat | 180 ++++++++-------- src/main/java/mapwriter/ChunkManager.java | 9 +- src/main/java/mapwriter/Mw.java | 203 ++++-------------- .../java/mapwriter/forge/ClientProxy.java | 11 +- src/main/java/mapwriter/forge/MwConfig.java | 135 ------------ src/main/java/mapwriter/forge/MwForge.java | 17 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 34 +++ .../mapwriter/gui/ModGuiFactoryHandler.java | 37 ++++ src/main/java/mapwriter/gui/MwGui.java | 11 +- .../java/mapwriter/gui/MwGuiOptionSlot.java | 43 ++-- .../mapwriter/gui/MwGuiTeleportDialog.java | 3 +- .../handler/ConfigurationHandler.java | 84 ++++++++ src/main/java/mapwriter/map/MapRenderer.java | 17 +- src/main/java/mapwriter/map/MapView.java | 7 +- .../java/mapwriter/map/MarkerManager.java | 6 +- src/main/java/mapwriter/map/MiniMap.java | 23 +- src/main/java/mapwriter/map/Trail.java | 14 +- .../map/mapmode/FullScreenMapMode.java | 5 +- .../mapwriter/map/mapmode/LargeMapMode.java | 5 +- .../java/mapwriter/map/mapmode/MapMode.java | 48 ++--- .../mapwriter/map/mapmode/SmallMapMode.java | 5 +- src/main/java/mapwriter/util/Config.java | 30 +++ src/main/java/mapwriter/util/Reference.java | 15 ++ src/main/java/mapwriter/util/Utils.java | 19 ++ 28 files changed, 479 insertions(+), 520 deletions(-) delete mode 100644 src/main/java/mapwriter/forge/MwConfig.java create mode 100644 src/main/java/mapwriter/gui/ModGuiConfig.java create mode 100644 src/main/java/mapwriter/gui/ModGuiFactoryHandler.java create mode 100644 src/main/java/mapwriter/handler/ConfigurationHandler.java create mode 100644 src/main/java/mapwriter/util/Config.java create mode 100644 src/main/java/mapwriter/util/Reference.java create mode 100644 src/main/java/mapwriter/util/Utils.java diff --git a/build.gradle b/build.gradle index 76432e12..33e14cec 100644 --- a/build.gradle +++ b/build.gradle @@ -25,28 +25,27 @@ repositories { ext.configFile = file "build.properties" configFile.withReader { - // Load config. It shall from now be referenced as simply config or project.config - def prop = new Properties() - prop.load(it) - project.ext.config = new ConfigSlurper().parse prop +// Load config. It shall from now be referenced as simply config or project.config +def prop = new Properties() +prop.load(it) +project.ext.config = new ConfigSlurper().parse prop } -group= config.mod_group -archivesBaseName = config.mod_name - dependencies { } +group= config.mod_group version = config.mod_version +archivesBaseName = config.mod_name + + minecraft { version = config.mc_version + "-" + config.forge_version runDir = "eclipse" mappings = config.mcp_version +replace '@MOD_VERSION@', config.mod_version } - -def root = project.projectDir.parentFile - processResources { // this will ensure that this task is redone when the versions change. @@ -67,17 +66,13 @@ processResources } } -version = "${project.minecraft.version}-${project.version}" - jar { -//classifier = 'universal' +classifier = 'universal' } - task sourceJar(type: Jar) { - from sourceSets.main.java - from new File(root, "dev") - classifier = 'sources' + from sourceSets.main.allSource + classifier = 'src' } task devJar(type: Jar) { @@ -86,5 +81,6 @@ classifier = 'dev' } artifacts { - archives sourceJar, devJar + archives sourceJar + archives devJar } \ No newline at end of file diff --git a/build.properties b/build.properties index 32fb322d..1a36d4b4 100644 --- a/build.properties +++ b/build.properties @@ -2,5 +2,5 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 forge_version=11.14.1.1334 -mcp_version=snapshot_20150309 +mcp_version=snapshot_20150319 mod_version=2.2.3 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 667288ad6c2b3b87c990ece1267e56f0bcbf3622..b7612167031001b7b84baf2a959e8ea8ad03c011 100644 GIT binary patch delta 24889 zcmZ6yV{~R+)2-|DawFDz=43kz<@l+?TaQLQNsMYHpHl7B>Ysx9%#l3XnJr01^HiT zB_t64NuQwp@A`-NKP!+1bnibwBLbKU*nhWzAx=>L&4noU+SUaF0a1bg0bv9tKwtqR zoD5BDOx2uCoh0pTO=a!vtz8|MjBN~^onusV6!3&FzQq&tR{khg(KNSM=|JeLYhSA^ z4oy}>sKSuIDwu@8)-ZLNXxV&fbW>PaEsP30NpSEFD$|bzb&j`ByZ1PsOikVX`sD|v zIZzR(G&Sx~ut%FC6;2Cdpf9fb8i4{3uOr!S4~z%tM)6V-SGJHFkb#v!0P4IyzYEd* z-Wad3FMe7OlAld+Tg-I{b+}mL=3t+!tJI!xmh0@8VA+nLH*GkN&Y8xR@%BnEv{%3g@m~fQOaJBMn+dwtPiJ|^v z%!qBV)y`sh&|bH4FFwjD(K#^+Al-;!qfJy3Wf9U9@NAF@KSC9v=u)na#)SG~h6oCf zySu3`^9aJkd_gfwJInbHUu*))(QT%RPQ>D(fTK#X}wwgmtEzeO)9O9kBSBiCUagebon>W(j7{KGXfxt;d#LB zic;9AM9uA)`9EsL`u|l=aGR`&XJkxmFTDvbu}|x+%e5+YBnp4qH+| zQbik(kS4`I8mz^@lr_S#@Mos7uTnUNM zAl}1(`+;Fx<{TVmqM_Z^%#1GX=p1&vDCb?t`sWQr(O!KE)*Y>!OEw} zKPXG+#hF&DbutpH6BLtKVgjpi+;R)B)nGAOI4d#$Vx5&FLekP@GnpMZ>^94IDlS4# z%~qji#3_nIa#Z;56dveiDUlqs(~6x@g+Ud`>QJs~uWW3QJEfW#ZK>h<-kOEUniEY< z^;yLxt{j|pv~OKj!yC*dPewxcDnHrvY$r{Yg!5&7BxPBlmMJ*GpluY`5oF+^J2Bo= zTUdJm7>x1K3rx#H31w(HnD|=Qr=s3p_dGd_7t?Y{b=)$iapF*cc4p!fOYMnJh~}Y~ zgNlCw4+9LN!)41K_kXa#8-~v%flV*{MJ9m--Jj)X7*UR{;<v@o9rdq)TXM&AaWC_Aayn5SiY@!w>eIuRKN=X3}1|wUQf6HT!et zyFBc=(5E)Ap=4^LD0gNi#ILoas*_9d>b*h`sw2~q8OJRfU^K`F<1A@eO~yvgY`D!T zj-y$t)x=uNx>CF4>K)P$P4mD?G$4=LS*H@n_e&a=xi7KK@!o`x*2+u0*#yI2lEx?+ za9yu48$E`D9ZbVCmev>L*F|w?+C^r#C@q${S3hE^J5=eXn|P0>pPJC8;@3rbC@0(S z`{wP27SG7%w1G6A^*Yvhh#(S%z~1qRETzIEblJv4cizS*1|ePDq^6zxCQHnQjaBr; zv7-B0*l#q>-Lxz0`=Q*d$c3iYI-E3cC7@-l`9Jz-f4SZP`jy0-}hU!vc%j2_89g{#N3>f2bR;e~$| zhn(8emgHRfa*{k~(3etCDIFlb!j$d{b;O7CsVVUaK7lggb_KF4y2A%UMnRQ*8js^9 zA#8NX(6SsWsO%#%3;?IfKxEuR!h=zOmhEerC+nzW+wrOsIhoQq)b+Wmr;l9 zAU_aulod>lJp1FS5M$fp;x#`Nbes+Rw(o{EX||7x1@Tv00Ih0ppl*pG4`O>~#1^e; zcFKW1t-c@P^0WXg5e#&X1T=GV&j|B=x~jkz!ZceMt_56m`p8Bb*HyMKfJUFF>FH*hpwf^Byws4ZAs_5g*yd0qqT zcOl_!9{BD7jbGp5(`v+Ti+wE5*71*^u3zIHQC&ZezC?1$oRGnqe1dYG8v~(#i2ROA z9Fd+;&nX3eV&Ew?oA3yKuvXI2O;j)+Z;JaOXMFqw>>OO zojV_%E`Cl6qu2wfMk(7-GGfVm+Aq|x;XUW_w+QgxipU~axFmA0Z zR>z)D_qk$T^hV>Y=-Sx0R;2{l z@B}P-GXv-2LHbkLMV+IlB?Fl~quatm6?+JumA3R4MEweP6zm`z5y3eze|p^$x@UmY zVayMr<69pF6RF~u2Ah#+lZleD$$J{cV}8mH-rhq8s4)p` zGgs;{P}OaiHm>sJgr|E2pPyY3tllAP(J;P@4wp=16Q6H?~nyZs#7|nFqu$ z4RvbjD`QbFP#31$(0pKjCig3yDOOx&U1^pnq5+=m;l6A3iC;@Y0aDE0I+4%BTVr0X zjCxr%SY_HSM^c}u?Y;uZ>iICj;gpdyi@_2}^aaA`k#}?j%IFnk1>G}=y6k_1J)(=y z)!FTixMDuCz+93z;yJt6hj1`kw+JbiaD(J!K;kco7mqjZi_W5g3U$(HKdR z3~q40Ffw)P1F-1El#V4ZubNTW$1NlHV}MQK@hWMuUSYVn9D4*vqk?W(cyoqk7(V7a zgUVqV!*YF^=cmDeMIfj^68+vZgX8J^Hr-SecWV3dUZWtwvDJoFp}KT9Mg~xm=iYwJRI$w&X|(pB z*eqfPF>?|_h;v%@n$NN9x&H94cX8JxG~HdIua{NLG`%V)U^CuOQ@tyca2q` ze{^1lK(tm&U1evqoEmcR?3XNQb9{Syo45vRwlS=hSn-l@ny{(&VypC)J00ldOckQ_ zqQGsIhl;XBt*s6Q~}wsKpE!&8}Hp_CkbBD|5`= zS-&~R7GW~q+G-p)uFA%B)6`sy?G%@0>aMmsopC^Y=GLeR#ai_pueQq1$~n@xpIVCw zsdeoyq#pR8g7w+b2z_nz&t=cODse*gw9fdrBein<3`kg0kPH8Fcb7AZm@=1>UGo|A z*6n_)`wSF^b-M5zS2vt-4b%Yk6Q`dB0%@&LdIlM5>iDlZ%$wWZD@F~(8|G(9>$EVR z0Z`VVstz095m92Aw2xGG(w;IWvNRzwOf1-dZuKT}Fj4V?VB*>F4uCLI=wpP1nN8G7 z4Q{%1OAEl+iD3PGd=@-f8f&JQ9Kb0MXQj+|&G3>c(_!kTpaaE`jp?kpQ~rusqdqk# zk+^|y!K%4`Ix`_(yW8oB^e2-@bdcaPJNbK}#j`3SZS(?m7t&diEo#J*UGBBJ5oYRO zz_W^SpaUTT+hsEZ4-k8~C&bpQ6<53#?$u;~sO<>5;Rwl@k4*?OU-VI*%v>4eh_U%f z(T>2i=d>jwBGXCW=rU@^m;D?0X5ZQ-v87@t8|HBpjcj*h5lBP+UCrV#Ao4`}onFE( z(qxFSI=}L9o>v$ywBMGU+9kE|2daq_6llT5+0m!}aM(z5320+MO}Xn#c+MDokKo)5 z)#9{!hLnN7U@qqFOD-E$Tl2TmNlr$>P&PsQ&=^t|OP-xz7_?oNEHB8^&h9OZ zJSc7@(XX(v_D4DA6Ln9i*}>ut;{3LLv3;}d=sE; zGj3oFg>CBK2!Kkx>Ly;!_tfQ`7l@ja2aX>1T;saz1VFW)T|V$d6QY~i7CN^XVf|Dv z4{3M8(#US`T%P0HY)E8Jgk~9Q{?a8BCJe=;AxB77x-v04uF{Z@ARL9wsTHD@U+~RC zf7_axc!$u_oVmp@{o`t0XKlY}T-I`Y?ihS#n)e*C0iYdUzV6w^y;^Ujm6&IyeSQcECC4T4=K9ng{tQuEW5TP!mVcQ( zC5NzQw$Yr8g~VFd!lv4ZQv{AM+l`=DZj8^=ik?LlRC;)Sk}J3N=XuO$Z0 zxA}~kD|DyT9di7UvJ$p1E41RFfk@KNgg5 zHu*)^lZVig5RyQD3E+}krM z(PZ^XT}sYvB65V$_K|c~yL7!t=c!hV0?kRbwa#bUR#P70P{}Atf`x{b@W2|W1#6~d zeulA_7e>I3y+A{2{l2OGUFaVe-DgS3xK*?vmplP2G?peT`o8s^zdL%k=ITcsD$jXy zD8mA4t_&msdiI)r7*;Kdh-;WB&O)QB53{@DIrmKx}@4V`jbO%{dy zkV@m0JRm~CjpRy030>-<3caQj4Vj!0T@Gfua#R4wX9^?cqkbOo3W>Nmug?0vFBtVt zv2^KjH@$f#k~Ff3h`E1LsnQWNFFjdnz0*?&3ZLzwlFCfyb4YdKX^C^Hw}E^J$z!-% z#6TP1(Kk_zf@+FIUTw=rW-t`aR4e5ae2A-)cfP?V#9@c$U`Uf&geW@(ukFCx-!8(@ zn+VBy!d5N%k(a6BoXXSD+Gp?7^>r#J1Q)1y_=hD`&LqHcb5ft;jQ+|P`Bm~tePkWX zH{2-b6`E6@I;?Kc`WN(niEUQv4EA5KDGS3AmI3>;wE@^k-6Y20{{B>f%s=GW`wap$ zkgL);wpA9ecA2~GNASN$^d$?(?+1|g!dP=k8J+QEMpCG*c@$>fvR9h`-{0?udBK>N zKaSLfl){1Rl*^TLXlW_tVzkquKk$b+poTYG5oJVwjIunf0dpNT=dTe{J9&ei1!1=J z+1d}!kN|_a>kXB|71Q)3`ddF@4l>j#9hGSDgLF$o1a zO0`4#R@ViaRe*$2!*S{-CUb_aY7~BroZVzQBOsKewUV`$oEbMU#X`u&RnW!%dG#xp za)r?mhi;yAcUivO9eELt#595m*jXUlZ0?+?q-zc`_}CM=vt4?`D1J5_-Ia_(6?-_4 zXQ%1?9P2k5AI0i5WTyQrGDxEQz*#Fa42uYlvsf37k2ka56-pT`AyoDD{Tyysk&4AO z1$f>O43&LxW055?=JqQz4s~u5so=WPQ%N;6Yv5;&zGyb8ErCxZ-JZs^eD@zF)v(l* z52Ao1FmNGBw;gL^(P)O7i zU$u;eoGS*YID&T-?cwl%J5mPN9MB-f0s`5%FC8spz-B}u6>v$?{{}b^f`^pzCf(Y$ zDG)JT<8wNUgHTf@7om(}vk>{)L&1(vra48oi2UL@#<3SXj3HQT!^p$p;}=wlo&9cA zNWQs(H@d0}Tl5hjP6d-QB=g@Qovhof1F!pPG12EzTidFe)IThCfduM{Y0a`pFmQn5 zidt|}TA;q6(;GrOV5<*^EwDX_(mf;pPw945$*}@^^ke|D3h4i|Sj;+14Q=xu3JsbA zweuBCXh|fc!;2zd>rv4WB6doyOAxf&#&1$yYx~ACp}p_HBB(|h0ZI4MZq>rpR@^Q- znJ+z_x107mPouNUyC4|%Q++5Wh&WdB^?Ang{-Ko3X}l?F88%9zk+Eu_0gUHk2AQNO zxxWnNChP#)MmXh?qh8B=HQGD)O3k#a+K$!(0w_7EA2ell zK4g5TZA2nQtBwq{Ht@TxFs)jS-J$DuqT4M~8H{oRMDV3G8QoYp_MYuK$ zHlM6k;LGhewwLXs2&G8^Ou!WCYm9^TJ%7iV?(1~M+Vk`v9F;Hg6D|6pR2&vUP{o@` z>YW0n>l_CyJCv&!u?9Vun{kMqdtozhHl6VL4PQeo@XX$``&s#ggTxQ8__YvqVP!fE zH_}ZkwNZYzLHw0P8ilC_ryEm|OvtqWcfdbXbQXIM4f{nZ?r2cz5Rmo^+VPC4ZR34^ zyWNq(AM_(Xn|wxR-T63&w5GX7*n5%*l^F%#mA7o^llv{wC-GxyH2(N7?HGORQ3~S? zL*0{#qG`nr4^?@GqC`0HXPXESwNvHT9@G3JS(x{cWjP^PPE2@jk!-Y$Q~n*{JJ}Z# z%i6`;A2wTqQmsT9`LOB4q)c@d4i2S#xdy&O;GYz>Z73JGk#d9BhaY@M_l;@rwnWBc zCTtkQ!k~pm{3KCJB-;j{3h{4{|5K`sB?gJ0|M|@R!nXK33KTMu1z;Rw`t_OswWz>D zLqG!5OEcn4oRLAJ=9)+gib4hPWuu!m4Bcg+xY#z+*CDQkrFE{i_2)R%z3X8%yaJ@r zgu9mX>k9s?6e#?C_I&5_ec#Qk<~KKUYs}oPi}>|%n)#T0yVc|TF>^EgHwOSJ_;V+@ z9@4!gkCLWX3&?lC&2z;yw$`9f7fu}HuRonk_$FOowXqNF=xT-UmRS6BeGrzcHx?!${AZrq-^?8hVACjjh4=9RM2Q+1%0A`3;a zs>oXN#NQhKBs>@xyq+48Z(D15;ie$$Ot6h=aou>8u!5=+Mg6p*Ibd;JKQhA3wqu_5 z?lgRxub$|Z|Hj8b7dbu%jyeZpX zYSQ~Y>4B8(USvURmDv;ab$l=t&u=@8`sw94V}pYM^GDP1VFgomAs6pw(I#}02<(99 zdsSKr&XP^g3n=T*4w|Mr&{8g~M~!EGOMlCMpz26x9l+Xoov@T<*8$df@i@3#x1|be zjq91<;|Nx{_L6b^d?}%;%s8jsYeQHm?&2PIGNq%hz3Wivj(Z?WZ;?+I8y~TNw|FND}+lY#oTmmtKV=eCNPEq8wW4AxBD0QTq~<%TV_9z+_tOf zaiM<_3!u;Ixjx}*0Bb~J0Iog}d(MTEb#nP&q0Map_nfEEkJy%wPYtm$71prX(p>`NP#jHNa>i)D-U%y;61S2~)mPd1ny zUKMcN_6&UandCQRrIo4rsav?AbJ~18{y(cj^|N94#kV7ZITAeM&gxST%(<}NOwk8> zOZ)mMxyk?D>sNr&H)+bcXJtIka9XYN%d8~hg1~t=?H51j6XL;-Tb`FbwSdJk1HPM% zV<4mW`&4^k9kI{1y4ayuV~sd*qMH)lLqGG~jH$}b1(Gqh>QJLmo-B@8%ww<;d>BlJ z%TDgLM4&Qv%x!%|{FEKX4({LfOCoLB1uTS2zT(X?_4Q6z&5eK&FY2)`&y)z10XTzJ z+X}2(q?xy)L9HpW7gWW5&i(xkfCRG+W6-YxOdbVdw`!M0EtNhDC*4GMSfYh7T&@ju zIvx{;;hLHIzy32jI_W_qSUSXwBW(4x-B}U~x z3pV?{mN$8Cw_brVb)5}~VVH4^!RFY!Zxq)=qO^woB^HMm(gj9P#q&JDfKYQq&X5O- zMT{bgM~s2_i#ZH+(MnkQ+B>7!its5Sjw;PiehYmQbn(R`)@b zdys3-^AzIyy(L1tEf}71!CTJtUs+NfVy`@NL5fFcin0x5Yc)2lJ5 zB~z_4@9K`cRrR}X0?v1Bu0L-!#0B%Nc*M{Cvmx?D_I{?kU>caQeGJ>^-kE0isOmam zeanGnwbt+WnWak37hixkBP-^-pu9xqHNG%j>Ctz|LG}U$TfCSADq=I?z!IS@#_t|i zEL$x&&LYgFmq)p9K+WOO$6pG?9OMC445)B;O>+H`s&2`80A_2{DhsLpsN+2p)o`YV zW>*OCz*ZM6^)AN)`Y-COGQ;-`Pgm3yAj`=ut)T$p#Q@!ISSay}2y&lIKlE=9-SB9_ zV^E*VJkG1u7L*cfg#;r^y<7tYl2KEAc{{JF9w)e?nNS+B>3!49{W+^v`5wx0>s_9v zq9NRYPzdc@5S)rbn1&%jjKR_+bZF^5i@*h?7EjAQPEAO3+~Ny5={Norj;SxKT`4o& zpr*oZZNOj4pP{3|4}brk(V~AZR0P&o_0vEDD`|k;>bw#!j=jnqq$mQuy{SJ50&12K z7B)*d>Af-TG{d>}g4l#Ftq8YljbnOil_2O=r1;F2LpOA4r`~)`ecX<~I`(88 zDM-16VVgERXe)gjGd)b*a~)$M9UHx&<>itHE=XdCcG|O#VyQe2!c4UWgyX}NH%RT?oIBu8(BYKa2&_j2H+b${J;kLcatv=5QK}4yz5G&3eo=#8i zC6I)@?5o{J2Vd27C$V*l(!dbMF3vu~rNo~}C`ib1R;}P_9#LaTB4)UG9`3Y81;}h1 z&|}}t&gc8&ia~mpQn(Frt*UKV6A#D|2)he{01bM&IgoY>Ax%sM@i*jy$Q7hhI{VBX zOKhr{$|7|Hy@&rP@j%_dM0!2rR<<$>U-a7JZ70eXw|W6EbAo1ZOy-=`zy*nkSY*$$Bv~grR*R5`Sa#EiAC4 zB1M>1K}r82DUm#}dNm2v1YNC@g^%tp_^zkw<6`6{m4Sa+a_>VT=I_++A{%}Z>L%+A zG9|!>nVjXEZF~1#{s&^f-*rPMnk|cpOVk=~S6`uH?7?M^>e|2~QpOeo4vDZ56FK>6R3Yknt+3%q8jY zOS7H^!R$3jE|?Aro#ch88wP3aEtrjlsP=+tECj|>uBWZC=BA>I5XbE$s_ij5w0YF+ zrEDOY@;ONK4~fQQND+LZv;-8~X1EL*Tm^a66fAac?Jo4b>MpCPvKFT299AoUr)Bf` zmmjFEVvWjZ11`q_!^PD=4z_VsZGN1Lu!65cOCR_gLmU?2RL#2j5~==D*0>s&tt4_V zO;fGXDw&Ou5@YUj8@VA3A=yly_JtFli+sGboW#eXHLD63ce)ex<1c)Qo04Up%X0kY zW~X5TGaX_3Syh+9JXk1~1@~+~W8rySEl0jA+KT01-3?@YODQxrk)jCT((khAHO00;>x>4IjsS*01&PJKgQ+q@w3SAu&5s><-U?$E@plz_ zBsL38So;Oq`X(5VKkH@0wE}{=;hw`K#4YIHZVqyyKj4TAWcxo}1%=%K#tJ4rWqag4 zQ%EbiahIkoKbH$O;hqh90~PMd1Hpyg5ptuhv7dhYwiezsAZBjXfm^^a*gv&)Cv^R7 zq}s3Xs@=~;=C&I}rxxbpv>%(|uB$v%b>Q}UN|V={I6bG+E0!PbHzb--hr4C{oNG6- zuGx59N-o}mw{Yid8S0`Q;3BLTE+TAoRmmS`IWW(d*M=U3P)&w%x~Sh^(bAINPDz9< zDzLw*KP~wBeEx4kERVVxB^eeR0V$Gme05=pAqp_B2!3)UrK%Ip?eVcQX!o5aG0@bY zu+6%#M-F9r_vJA+%i$P&XQIYg4vy*FP0MeD63sLIfz--R;wPCdfY~%hc!E!4b4#V^ zmk`Ax+X}x>Q%OQ2eYjMclLI6n8j%rxNZZh3M8p(xI6{q}<=|Bz;QKvdXCvXz8QI9^ zrsyw5$6OTANkgV)Xv8sJ@el1T(I^DQ(1g9)^e?{jlS~bVwAXMr2^NU91$hF>2je8n z8ntQ1U$q*v*?Fl}0Ck?5;Avja>w4>W=O~(_kF7j4>dP(=HEQyu?oeP3&{`J~h6jk5 z>~VF9>Anokm*uGUM|Ik#s$n%9Pd)$qr9Q`Luxq9i#yJ|#a4}&$e8?)VMKDi z<_=7XdwXg8-Ao>-^EHEqCrD{_JXe2UgUzMkT<@?-|HYXGpjFRgJjk$mBeh4OpjsC&&?)@N`kG~)K zBrkAibbSAJs`NiYrT>CVmW}Q#(Av!r;%{MZQRAMQKPbe%+l?k3R?w*bMo~f>Ha?&r zAn@QIAiO|F4|E_wA6+AXf9QWL4^|tE7HME*fDS6do>4-}tJZL23Ug=iyAeqY5Ic~A zhy9KZ99)4_@|-e&zdH$0)uqiU&u*_gz&F%HhKG*ZC_I^-8sWa>XA%Ow-tn0GqSSA% z(E@uFid|qxpbWqg(G=K^6a2GdM8DmeZYIPO-rQz7Vft9IScK+AQDGhXxuR$Iha_=U63do@V=c8_#+`@De z8bLM4@SI4R_axV*Nb2Cy%S8JzMU_xH% z7q`^V!2XDAcCB4$*|>JC_pP0M(YM|8zP7%+r1}D!?xau2GEqH`#(B?V{bO+XT>kYr zJ(`Zo{V6Z%{5nl?o%c6&Huv}ufc^HVR@e)9e*07}FTk6>h(wj0k;XBzD3!WW2n-N< zZcr%s!n4MMe&8AFkT2xXmPJLb0?vo1{O|-aJNN36O_yd0I8Db(JyRVf z*i*KgJW^qzr#n)iMKFWirF)yg;#uzCdE-l+jaLX5F~4XEKDE@XUS!Rwy$6fIzG%v_ zcBwcP6K>Kxq~y&eSJ$jq^ki)ePPOz&k;jG^)D|G`n;fQdWp#G*cbj0MKXQ(pIeqY4 z&?&!vduz&JhPk7Qxh&oUkm%GP-Qgv8+xjyn?Z)8ME}pX*`k-P<+IP1V=z1OF*~8oo z7ia+Gt9>G#IH5d%n&yo&sSjA$%*JeeI$~(Ag<7XrEnr)8KwG?4HdJ6eD_-+~D=J$; z9h$7MhC9_@y@fF=QEbcdFfZ?PTYB^`2NIiHIUD-QgvCH4)xbF5PM$tByu438yWI|d z@inSov#?%I$=fLgS3&cBq$s_KeJ7TXnR{F}*s^KT0a``Lmph?v<=MuzOHNKGbz`Ln zvsD5ePa=J!EWvr;UbLa!n*Qj5rI68}Zp$iWxH`)*#@G^k>4x=CeWfQ`_Du_15`lbC zTeh@HztQgaB9sw;*!+jSrK()7)owThQ8r&~b1K_RO@o!7JW|JY<)(te3{6=K`$tUV z`T*0d{5?*xkeSya{lMy?~(W-4!Boq`@~b2~o? zDwRd>4-654{?IN`CLLIvukQ!9a~Sm>d=KwiaJMIot0;HmjO$=q*NbX}FV8L4FGtp* z3)?i)t=NdKWZu_(x|N}9--ZL#J-a=! zy=_^}Q;*T*!DnTz!knI;^JhiJPnCq@6U5Y_#3U^afX#-Xr}Km$6j(r(r1X+F^n;_< zIElC&Xf3^XWx`JNAfg!;r#>4|*w1cM`baYuXC@mTr+1#YL?kTG7$F9<^|KWV%KE+N ztAydfLFR51meYdZbtvjkR(_Su^$3{OMz{$3p#~H$S%w{>VHGKpxJXU^R`uh^B}t)B z&B_5-K*Cbv_63y96+5}!+LE~#(DAK%z%HsG!LtJ|MXkQ32qLdCcuX)$gz$oU%*;{V z3WuG%F*wwr2c{}uWzq1)EF;BQX!R~Tr*KYc46D6--)*X`CWq_k{-|T7lMzcin2~8* z^EY;sXqDNqV{5z{C_Qm3tfLcEV)af3qAbJdX~Q(I@4`ViW- zNq2h8ty)>YB=;5^0XsFqXmX1qaomvZPdOWJc4Wu;mJKD^;^}nGG<%_m1qzKAXnd>p zbKeAH!$b6b6@h9~ktPEM*4s=Rk91PVpgDJ08w>+fx1Qu#Onr?9n-zEeeSMJT6dDv1 zU|Y%^*Tw&afjU-xviy5d`|&!D^SgWG5L2 zF#yLujgvFYlS#?h;@Qg&I!*=#rJo=) zy5YA;MYs|t&uSok7kGc{`<)BBKO(Qyz4&p|KTc1(**u_K&`52YtNq z*szLtmJ zB{S|#?rR(xx;@N}r?jB9Wm_#i5rcZinXNw~O@{nRVg`>i38KV1qB4!=i*RFw=Vsj4 z;9L*(PYzDpJgRU>Qv`h`^efg`omZ%#s;+%vesjEXpqdzsmza8Uy6P+8gYI_YFLqBb zW=={Y`epC>D}_ZP+m zTgRsYy9idbmHrsZN|oyb=*=0r*(c+B z@uheCz)EgQs!1KgABtsSOB^GWY=?)Sht|5zZH)*WY-`uc!k2ZimE+FWQEgag-XbEM z&(0s9WTN|IHS;pASthbm5fQ)1<9)U}kU8JI1JGZMp#ahEP0OVV7AtTvAsOa#mEVq*~ zd|;Ug2k}`;ZcP*LK4!yA3#BaOmz{jBRdJ%dLA(leoGH?LakKE!k6ufpB&@?&;6K^W z&l4b*>Ob)wryB)C$%R@{{&lO=NjE?0GwG&Xxt9_gU{~r{@5;gZ$13QbXfrqYz}cs zrKZDSP8I$ng4EWXzW+k=V_Ijv6A1*L^XG!KwVmzp3UUf%?JQfZ4juC=m-pL0$P=_#E+MNE| z*p>(h065>4LN*HXeM0fYb#9sSjHJ_4_lp*Po+~R|u=$eiTE?vkv{V=JN+at3G<*`f ztlj%7@>>4~dDUK!m9vQ3kdf17IiG=a1o3Vbqg8UBuFsNKJ?UY+BO0s<7!v zF}jdzjn%1(YT@(CTtA_Ood0Z!@q?>)p%o@pg3ivPiOa)@E0oU>{n?gwperqvqoB7X z`O}m9`oMN+I@^WkwwV4EYGW{NPTvoqH*P^d_q=vr!}3?J$m)HV3;*9(yMteIjDSy# zj^tk@n~(qeq4?|_Z?HWUTD!1%*Bw+cXZ*zNg-pI~A{%59$`7w)!;9D{S4@2-wZIdQ z1c0LtjJK-HKs4CRTcj^uJ-3{*jPKXS_c!YeYt9+E)%J_c5t@}a{$yfsR8{7m&72T< zA`10sW52VH*BOm3UVKeml9=s3`2x^}E2++!n^wj+Fy{fX^j!qaiNq-mn^~D#Xz@Y7 z@LO*JQJ~ozWMmFkK;5xCgEY6mv0ggr*1}8x<7WN(k~OdpaCT1%1Md%^6Nk(C3eB}+ z8b`h;v|2}*I)}BA$LexKOL|EX_|G3Gy}xSD3WsG8lR4Ao+N7anQeXyDp8#_UgVX{v z_~GN_b)2B%V0F_bYo?qVRvw0opLL*qJrI7K8lX-nk0G%dE}{=ybraw;%=z|#BQk}S zP@j+g@Hc#9>N#dKW4_dcIngj_NOtC#T1Ymi=(qKqpZTfHi34WTtS*9*+6BM^H`G!#^Lb93 zrm2psc$TV68Defz*Q2~Ti8-ok{L-NbJEslRuqZUs;k18@3C| z(2&fwP;yaEQf0j1134%wK$Qf_jb8;Reu2;0rs7`dJ-{RxO9C{;*8k&n-Wx{; zKGsS$kT)6Y%s1E1KOXsE@=4?!HIZa!b|H>5AnfE}JN{YyLAVk7jGAtm!g5B`dh%_t zDeD(_*@pKQfiY(s*8<;;g!aWl;MLNvUO{-CvroScgc;YEz(q>W(IyC7q((7yTE$3w-{qzd-E7Z$rZJ9q791zG0_#n3Q z+tbsDi~(6VSNW%oOGSCU2-4By7yn-!R{<4O7p)O#hR&fuI;1-!q(!7Vl>sR!X&jIi z5Mk)&djBySEw3w2+~9VUSFlriDyQjJ}Y-+3TaWX$N1%r}cAS&}m)Hi&B@4zOwG_`rPNT zy}KRhI;MDa2lVy~y5(^n4dP3|O-s)t1nsy$Z5j?e{&t%yU1-FyJB=ebww_Lex1d*FvdR z?^v6dYx4R8tJY_9A2oU;>z(EgXY{>q+irq$c05wxy%)8a@;+Sa5u-0~_nzATr((x& zZ0_NmQ;vN`Y5q=?=W)>q{ksE;|2rvVh9@JyKM`>q-& zcQ(-|S;I!KUrJ-gW#@$PYWQLd+$VAiZ{_u{qn@e|^pHQib7ta8AFh%UPTPTJCDBlt zTOIR~SIv7w^z_rB=*DN)`ONmV3#3QAuh2*)D5{gTSd{g6OX;J$aF|K8<8(OrR<~c& z3`mwPdkVold&qEV=%I~kbC8ASgDl3i_IA$~t%K=ZKOClg5rVI}RsVbtPycS)2!&e- ze(qiai70GckF{!Co^CQ)>x%Jy@&MiFVFW#N!^%9O?-_F6XEOH0^_dojXA3gIB3^png64%9Aj`nSjCIutUD$MV*E~DV9KnXu=iiXEvG~drX*3_gG zF9WSIeR{*Vpk1u3ue`!yp{+{@<`V;sgp!Z+b`CBYq*648`!UgxnPX9sRSUPlZDCeP zTTXn9#Ez+P%wjxXh?}Ufs5}emrrSey5GZE)DaA*PEtNJD?rqy{Xa$8 zier#n*m;r?6t6z6&g6X}YsyQVIW8-BhRzzh*~z6mZDSqnx>Jd=_`zm)sae2#MS(TArn=$ckfrTo5B;5aPV zv@1EC%I3h!Xlp9R^JLmyuk4_~J?JXoKt$I4X#3ObavRqQYcht%p1;iEBOGxnR^PSe zu1Zk}43s@XyNt!!6scz-T_xi6I^PVr_Jy8A2!Fy0G82hnxs_aiVKyT(zmz%c6>%O( zs(KLwEs(8TvGeRl3YjJw_maviNs-^3cqyRsloX6b*2xPx^fp0}$!@Nd{%Uv_yZsYO z?V0z_7bdN>YomQW?1QRduPw;MT*zbAV_tKDEKQ4TJj)(~IY2}U`I!gv59Q9pGR$@Q za31hhy?VWqH2yU%+l6f#)C=q-i~Hoz@C~NjgYtWSkQa5#O{Lz#mE8~R6c_(wMZV+O zlz)2s-m8V{6WZ9GM-~go(}Lplk(CgMi$>7JM{>2eUS-pV50gLUy^k7ArOdZU%@HX# z_(twr;~N$v>Ve^&mGu}aA?s8$2xWq|zlimNdD_trTo6$s8moG}#d}zk`0^_V}spv0AU{^vR!}h-7O9FIuZ!LP{4kn{Kd43S* zWRRA-a6hGyIY5ifL}n2;mwPp&_ys3cu`4@yt?6+$Zu6Ivm#OJ@SolYIsE4HCktqSk zj@kZ=F}s+$C5AXOB%~l2tN&uImf^IRFq1rau&c4UYH%^MJ zhDGk!GAhCxLES>A#%Eiv`?`{C>i%kX8lRpZD<-F!GSoYV#*u9;rCGBwrNm0~4f4C0 zV;k3Qx6on%ru%PkXd-7oz1sv)l+=OR4%W%EX|T;0TvrRFJdf4s^%cL6bw-dcw^Tl)b)|R0r zU8Z{6UeFRJs*@UpARnP0;@rD!|uo6137}2L=9<; zUQRQOw;Va$dMEd7_)ZS*-#1V|ZN`vOAX$9R(^=WU1s1Xey>a$GcrxkSpLzfucI)A| z^U_N!ppe~&_=J*Y@8kZcN^-uT{M6n_I3($XNgXuXh4RJb@WZ@Jpa^uOZ%Xg8R@r0y z`&-71+;DhpY3b_SkSmt3ik+@EyM6U`X7li#OM&95(b8pYtz~-r{W2u*(6XLmqfr-6 zR$U2e{JRPq>M6l537P{;mmjB^_axwWn-){)%BNa0ZQD5oWK-w8cjcM?Ui>{#KpghtDs!gW+zNi}oi!`z&pJ{U2#ScR zan3$k;+#!e3Xo8e&s=nPgSeNP*dAa6ETJio`pGPgkVlNU9b-H; zwZGTHIMga*b~^x*ev^ns_^Ynn)&bdD>($PktTySmmopdyMA+S3q1|$?zV6{yD+Wa< zLaXkFk>ck+iyRGhB1yElYYsYPMNLdUbJ;s{Iezx-cIbC1gBF!T6T6K7RZ?Y_^j>6T z$1it6+f#Gdj^eWjHq7HWT~fz=1x^T8a8NS84?4gMiuVj;tJe&=xMUZ$`X-K!d8M4s zC;xkXF1?kc6}ao8LjekoID!4>J3ze=sD?JX7a384U*A#XngrX=RfRqz(!iH&FlpX% ze@l}6;tRSZK{GLyV1FSNAul6N%A`Oiv|-PXtf6In|6{b`A?B|YJhl5#j8gu1R%u2F zhT|#n%bCN&gUPN19_#y;zrJ6f`+JqKyy?cl5vx9WDw~^`O2N#VPmeCwQ;SBz&khk} z+X?!w{4PM(dv6|56v9&!BqRM^_KCsHs|+q97!WQ4oNH=h}PY1cfksH+A&3WA1NkSDY69qP53 zyB2D&{_Jw0C~YbPY22l#UdmvM>VEESyb(s{RW|$cVzWzJ>T`jvyHO6r(cs9FPjb_s zIO|Su?dux-QQk0qF~`T+JvpzLI7{`%-o6qH34XK|W!=VB&$;wtO;=EfA9RYXS|<+T zXIYVupruIqyr+T-ovZ878h%56#cf@@Ommx@8LlTTzG%A8xJHfR&S^glM)P`i`6Y_m zGkBis8}|q8t^93`!sKs;L&vSVT~sEY!ikLKoAS6XKg3IJ&Dx(9rDxblP!&dwQEC=? zSfjvQdIH=G?@G$&JhF)nv8mqZ=OAEE5psBN5D4DoU{H8L3msFJ;VMcv;>3#@qU(Y1 z%Dx4y6@~1|XI(G~GIV=k=HB{-^@EUvzo1?E$LLaoOoh(d2$qja;Y)lKk203ndyz9F zLA4t4EBrb41*H@Gwl^v+z%P{gTu~SK39ZIC+~}tc+G4CStTb&gJeF5#We2 zJukS@DE*OcjZx6gY?y;U>;qK=+Ytv$E(0I48g==dJn7civzvddEGSAKFi>D&ef=y0 zGY_JMebB{&Mro+2!lm*3CO-B~R+g}gFbH5NRI0HlX%Hi0VSaAdYPMGvu3m_{6vDei zg2pwfWuw4k$r94NY7X96tZ$s|P9Y>ukM_TscFm`(|EB$Kj_2WaB5}HJ`}ra$bC7G^hYE|&8&8+w2k@m6fRjJ zuGGC*;WDd3Au3A2Dl_d*DJp%sxK8@rcB>eDJw8Y1H^V14M!LQY)Ta0XcP0|ob&683 zvLY;~lXH!Y5>9;mj8dSqDTYj`G(I-L8^UmhIH8#aHT{XHC)2a`CD819*;ie|wSfu6 zCq~xi`B%C3awc3o9%C?9bvhTA?SE(jYIK`MGJH-hzaKo~M#^(G>opim&w-dKkh@ZW z!Gxq%oL>x)R2zp6!;?5&%P?kezI=X(d= zz1>1AIIRuiwRz_Q%iA&%UtfN}z>7)SM)KBwcO6H~PgjHTL=>Yo@gX6F~bMFq(1gJCc7j!U@ z#>OgjMI4n~g~2j;sbnKYC|YFH=@fM-aT^{lT#Eh<-$m~3JzcInp6pywi294pEmN<; zowwmDFUf^`*k#|DvKw$E)_F^c3Ckt!XyToEy^orz`fj_OaIQo=B8SHQgk%WPIP-8~ zC{E93UJV_zjv9DqO1|s#CL=&@`w}{%7T@s5d(O_SG6l`dT9zbDv!)=H^P7q1XK~YF z-8x*4S&rq4Z)jFCE7M;t@Xp%1)zZ2-7>={BCd4CA19Ms@`tdT0PL5B#qanh;?wVXvYRDHMeihsz@GjndjGRj1b)=1Xhq!0ZGWr1MV<2YY9Sfh@K60X=da|}HfMjKUp zSC3aru3ja1?9lTf-~fD1G}7sJcKbH=c-S$^c*T!Nb&Nf^yS+~-!U#;gnxi`{H*1f@ zhlwu+y7*B}d5&FZvvX!*sA5d%7ro|kd}z`(A>rFNk<~hpZv`1=#Q5w3KSzj$URovU zN3?}tJ|J}9P05MDyR}Off^u_@bg6GpB4R4M!a-HWozxQJ~f?4Ve z{Y()&;xPLp5asE32JLAYu%nkYzX*MCiR^^br$8|;#5XgXW4i)&=bYpcz)051IL?_4 z(thVG%Ol=7%2ehqxkY0d`Lp7j^<2sas{9QTu$km5 zy8KeHHVnB$Jfj8asI(YDxy9#bZ5wVc5B2-AE8eW?6pqgab?N(Vwb&PLZfdQf##Wgg zWJIVgoyopVGtH9_wH1DdX~5lzrHm;!&S|}j!4Z%qTT`XV%6yLVxzP31AX`ggIuvZb z{sw#1g08Z^Eq!`q+!bq8yI)+ic9hZoQ7Lzbn9Ys@Wo9N($rX`Wl}~3dMdN|wyR)d| zqy$G+JZyuPI#42^6C*WjAFth9n{4?RqXNnO{YC%R=NtQU46XVvj)Ka2h89>8>;rws zBW#=sxSgyBUK%X5bKJhr=Q+mk#Dsdxxac1#y!m`_YlV^n&HfTn3wz)HHbWg*zXF+= zUxpWr{p|zkxil-AO$gg}>h)bmJ1;W^l?m3G60CFd4Jj*Ykta4_r6{mMo-VPl& zK*Y5MSpzt2`iGR4RTFyi%9B@*h%=7`GX*lT2n!{nRvMfVt-x$j#TGraqPbKdKRIb@ z?$iGyyE$M>3wVIx(_P|b-)_?HijF!FAxpmvK}T4iz7q7qbjvgzE_WYw1+Gt2I# zV8w)?9g_GWE#9_vdz9?_Ya=pxSx#hM8H-powTovZv&P5$)YsahrbV><()TAWU5Grv zP?*3tA<5XwFr{i4?hq%{jw=6oV}5qojwF9^HB3)Mt~jbni#g z$D@oHt@}&8m|}-YWAfVG(%Y4?>1dHY$;~2nuBOowoNDdkncA_xtPEx{<$4=&%Ejv$ zdtTBt+J*Yfh?3*gp|dp6Y& zw)j4#wQP+6Jn^W`xYc-kW7i8T^y5oH6qUL$n8r_Zp_-*oMOKx}YO3v>0}TIg0;#kYCtA4U;`^NG*5gkG~Vz3&6{6`p(3dJg+wlRWG=D$CdmT(9hll{%24O73L8yXV-NCL^9OoNSot zQD2~;$1!)H1 zA_XS_1$!)AD*2GjJ#|QBT-+ipH2HiP%ey_8I3Ja#Ry{IR&N7cBz;lC?t zIE!6dV}&xq@gY6SZ!AC@(^yfssk4c)yNPv^6}b_!Av*V%)Z~Gd&96N3o1Ym0T1U3JU08D!=JwiYRwpz>o zSJfFtTPODWQ0@ixO zi|Efg5)wYr1#GE~k?tB{^YRHK7x-ohxbFN#AR*NTP~3u55s|>SkuhO%^+X78w9)Zv zQh?71$b2EV|1_u#xcpx*FRZm5^xM)4IqR^8h+GI*MJUzfhh9a zpy|g)G{9_RLjZ5+Ox^(gBmsb|Fz?3SjAsig;a>qU%5*y5x%>vufEvL_BaaU2Y9vIk zE_6Hy?*`1rV*&!(H^8Bszs)x>BY>UqbnoQ=AL{@GWY!zN1YQKtoSOvJ-0|Cmf4Y`P zNbEPjv=Rt#bJLyQu~}-mj!n42AII?U{~Kl)Z}T-`+Dqfp*B zNJ#WI4D3EcP;nz;z($*Y_wicyNCN<=1J}(-_Cy!9s?Egte{EhDSpOA20&ZT&Z?K=} z!n9hL5jFWRzZPP$=mR-gFrX+z0mEzsA;5fQR?!6j zXcM?@#d|1nIR*M+^WA1hO%b z|8T(1Da#ZAZ0iKUPEGI;19k24<{g|PMWC0eK%<*3M_Rxvf~a7l=46PedJRVCDF8ta z1%Asn*%=-q*c~i^25rClhd7c6u+9TM3*T_%zTF>J&|q3^R0zLso^Jbxt_^@VBEU5c zG=G`@oo@pKSN~ywPUblyd9M6LZZU_5~{OZ&2LJ^ z74rYrmUS@D6IK{*=kH+t+gt^-#&57*B_dc&I%yDryxzTv1f2n4+BIxItPfw-M>*rr1=1|CBR_coEh=?f1^y72dLcs znH@K>EH{|LiV$N6BwhZ-^kz=sAG$VRvlw7k`8^yX@ay5=tbpyn6%pS5ebfM!H@<(Z z0Pn9V5l$6V{2O+}EhjKX-UI8P_zkdbH3IyziUQUS|2-Vn|D%ckNFKOoZ-95}VD`22 UFo_-vTpnOKhXa$yss0-AKkzv|fB*mh delta 24379 zcmZ6xV|1q7vNfEJZL?$Bwv&!++vXkHcWm3XZFFoW9oy;m*?XTezHgsjRb#CBb6u;d z=B!z3A`WaZ3Jg(E77QE~1OyryL`IHFG!c;;`d{{XYZfDsR~3uIs%7u^;20F-|AdwP z1pjyVB;|kX6XU-vkm|?Yznvy{P*+gIe}$Z0YPwW{fPid*01G5=ftl@yz*g|)e;;j1 ziPJzpf`BN(0g0gb0qAPz{EQjXj0B)RK*4^51+c(`M3R64Bf=7e3{l6!g+O3(q$#Zy z&k23JQ4jux1Ma#SCi!JcWKfwf6KP~+r$QO1Iqj>R3yy=FO;QfLwt)$Zm|3eg+a7|a zJ3c!(Z{NF&wP2ngL}5yis?c}~bZMy|aUuId3n1D)JoZ$*4nUZ?+vLR1Ui$T|Af>EvVACKUPsbM|BmW$PlG0u-zCLrF}r%c!Z#N?tQ zOhyn1FniL0B^9I-L))?P6<^y|W4L%(zo3&#W-ErQw-jf-J-bXU%mFz<(u*ujan?LJ zm5EE>B5?x604?q^ZrY!j;Hjo`LzXNAGlc30)Q_tdrPr4jR8j2gYHqNvN$QLUvMQYw zEk|MAY+a&P%xpMwGF1{~)))8LSnt_Ca`X?Vr>^5)Hm&OlMkH<7feV+f-w#%#Y0Kd) z65I2*i&pemcIxsi22C)(>pDRL!_w2j?MF)Vb37)w0i7rcI_5kUo0;dsz)GX>2sbs> zMuA0_U$VTen1++BOM6UXqQj<|=fZ)o3QNU@j{(-1nTc+sOtHcn(1ixvLpTf8IFfC0 zTHNP<{A4atOvl42X{f?0yJ{x&wCQ{a=@@+0+JCY{U>zyxki3E$@Y>V;89@V#@@^vCmrWu9Ri$Fqu93!v3rQZRp*x9-!^zdwOftH=uPw zfXZI1{tsAz1RD02$6o2@4scYemd7!^nZ{UHHIrOah?5f zb}z{**FG=aFy9y^SI;zar3{yXd~=Vb7M(2XHQJgOUV%-G))=C~6Tl-*7=z%IT6HxD&KJ$xTFz;RsbQ?&OKQX7sCFQgRuN+p$zrFIy296?fs z+HmHzdWCY3!`Xzk#Oy*`0qG|hG-n3djh$z$PyXZ;9F@EMtj!K_dS^x0QKC? za+Prht0yk8rwv-F^4j*G!KvCij@9WgH_}y^kTY+XoK;2Cr|EhEr~d5;rortAA&9Nj zdj*L=cooM~04TbUs$BnSiyOQ++O0<{X}_H#d_f~q8Z&yls8z-O6}C)Vbch03RITv@ zL!T5l>43w+xM)Y;y9>ImqTo9?po>CrLrtaC6@Ln~H^KqlEV2+GCF+~~?3wrqxS9cej(p56l7tSu1vi4ui;%(F_&+#vvS z^D98=tVzt%DCgF6kmzn#=xq#I{L`SoS6L$db*#aNMTu`n{Ep1#k$Th#0A%lu%-eRL z_wT2#KK)MpIMzxY_fh)e54TOIXKK)&snK}9Y-^9Os$I*wp0mAGvKEf!iM+iQC?ErM z$HcNWqSTjV(n*MQ3r)(&#7Y>C9qFY_g&$WETt^?`q-WXC|3B1*0h8 zH`0IOO%p9*8R&n2Wd)fL;y)e?rZ&`nJPQIEr2lv+ba4N3TFe{@i}Ei3LY6hSy!r>> zXt6;+Xn={}m_S87T!1eAGS1(=dZsBRGE-uhtaMW}pd*AjnhE?c)emE6JfT@*+e6cg z{y&YuO-A9g-= z{&w}<(w)0#M|+QA%@ z9Lu6)It(Jaj_$WxVU7TObiICpz>R|hSi zD%~;r>W)y}N&_(R28(D2hsrQ~B?b;@TKAi11j6S&?jXEQqWyiP2hxr&G>%TtoFA%C z&tL?5DFS=1$2ie_RsJ}OAnx8Dn!kOv674G8>G>)QynMX|@_mY82oA;{-=bj%j?8_& zb~Hm#1Bmnb=*n9Aly8fpjIwVJSMT5O1pR6A`q0X+E&&@$0{A#Qo+Cm&7R48Pw}z|z z13i8pUErXJHczD9T(y)GgTbvBvU1HZ)l|j2Ypa64w^wNu*NrHWT660qA3Z0Lp)r)) z-4R+mBs+PUB-ODJACVrPJP_bx2`QEuJR505&? zP-U@uDgYItVeG|3QFzKQtd(PuuCx@V8RB{TII^&|QRypUo`Z{HhZ3*lB?=07>aVaC zJbz}NFB-s8p5^bT>$|^&8l>^BJK2T1t>f)}um^W5w1H!Gp)<2~Q(|(qcX@8GbXbkW z6zifW(k(UfniSJ#t<)3`q&;;wOB^;hhI6x*Py$9v8ov+`0w;^i51<2&0_{SfAmb_R zOezJZXrS^F|<~HI$9>HPp8o$-?>qdFx3sJA@kw-Bt-EUzWC3G zO1=Zs_P}3Cbfi|L)#VGhWU&PbFmzLsD>>=E)~{LOt;3ZYUS9)H*o~LmQ>O#xQk-SK z*1rsjdjXU%+r_F-1YTPa`ufSr^!LSKqJRkN^g%fGtq43exkE_x*rw3Vu-!wX-yQP| zY=VC)w~A({l{pj^yKuiF1gT$}!us~=Kz07c56|Cne(DVg-YP)+UA%SplpF%wp?}pQ zUwk}SA^a`!bHZ=4^d!u!gCWMGE)+u(P@<_{ByH_7>xmhIQ1`NR&y+-SQX#TX?*#Bl zvUkICE?5`R?aDn+zPtG}@@KG>Y97)_myHiFDxL~=XQ@$GxsZG@TVBK!7V4J&CSI+B z_kS^+5-CWk$B3F|Q=-PSF^1u%s-())jLOn%tu6JbK>)?*kQ5VAWgVF-*`q0xK${wN z7O$QctAVC5E}>A5d_Zr|Mza~#-T+*{b4#c&hKvf)7>$+2T$U#D6-T&bYBGvH5tN2y zav3OY=n;667;O|d1*fJL{uNzl&z1YNR9-MtiZL01XN-eH&^leAm`re*kjp0Gh6i+` z_d;3sIMXJzwlOYRBjaAND%5X;3(L8*Y2A99VpRyXEY|RuNf1SyOb9t)%>s}VqaGe9 zAF3I!FOYHA6lx{x85^7a5vAHkk5F{ph!{m2i@8&zbHe?^6c1r{`cX(%K}a5$d%>i_ zm*!C5m1X+cB4x&?I*ciAi-E=bFw7yYTOE0&{3d7KIzDZi;rhp3&B$kUm^|nwlp{MM zZYWHz4lKizo)@MF8m|~FoC2VI1Y%Vz%T#Tqm?a*OvR0NU{QX2{1QK(}<*dleT;lL5 zcl#S2+3#Wb0iL~@5lo-Cf^xGa@^^A#{Tzihrbg@QP(x(0_@*6Q<^0IxxP-seAcUVWdcEyn7fZxpZ3`#~r8368HkAc{`5W-W=XSn5{=W@Nwo?vA5X?!D>e~S0(hdRoxmhy@_Dg*|Owt*a(!;BPH$MUTltKOo(RIlGNz(jy=g8eE^@Pf2xXa01% zK*^X@o!QffTmC)`Dw9%~tG7jXxCf$V_MP(_OMKHWb1owzh0beSs!nB2&m7(v_RZ6s zE$a*Z7xK2KP*m@1gTk`0S*+d-u=w1FQF*N+ygB^lw>YXxW%1?oS);Vf8_itvA_aHv zD1VMiTZK(m`(%LaJ)7o-9mT0Nps^A9R<#U0*P z%wg6ybWhA(tb*)^U~ZSUx z-}!xBm{Xj)@fc0zcJxT8oU_DS9N{S@foe@$4v^0bAt&{5@GE6b-$D9a zN+V9BzH0z6`9Jm82%3Qs)*B(w^D(juLBDhZpj-E3Y)h#BnH8=+VYdQFEl2d$j@ORr zt2k>#vlWQ0e~JgW(~Q+Hy|qS+Q@)O*3&Gquj6T&%xlzyLhREwkFomF_OpTWyNjky9 zzFqFEY6Wrdi$vzeo+4j$Ao6_hz1DZ6y z=*#=k4?wQUONluOhLp@Y;6kwy*t6TLBr(+dZ_Tmor^KWo^i*%YbLk>d__-UD_cg&n z+L_@Natn0!p|d5x{^Ekk2hLcr&E=OM+Z!NmMbY64jEE+0b`z=G4ISJ!pl{S#a z*6;&f@>y8I?M&oZ+h5VWY>{-6M&mY>XtBU*dc)^A)EBw9qH|c=A5|sN^;p|4i-)SB zT05vnCvfjUSj%C9b$d|Rr*oHGb-}`LAd9pvmgkii2cx}uqloWOyOS^c-RA!#XltRAJapx!NzEPu`O$bvOtPa7mLzL<+1BpA;z}m03LyL+*{3N@LLKry4EjzE;(wU-`!83he~Uq`+%!T! zcXdfz=wI}TOe{)F_023C4J<5*j_wGEN=z(FY$w1~b!r6Gf7rH`=OfGXKXMNq5J7_& zFkwIR6S?PsRt-5C>^V@@A*E6m_euK)A+H!D9i-0NXOf-$%}lr17G~;QvpCd9adtpE zuM;9l{YE?PK)Y%1S$e9-B+^RQE51p&LD536`QCA&^s2mM4I9YIR+Z5oy)mC--Wsy; zL|v8@Q_}Qs-o=hJryrS9a-iR2T?gbETCD33fx1`rfC9tu3CBw650fBMzU|{(V!JlT z9Uozgl&`=lFp>3wgq9=PSL@s##jmS2rZ!OVkjtAm%EzVvZ(r?@)TO>V+4*$9|2L5Q z>ob9nnzV@jaw4wp4NpNqKoX#Uf|^_aH9G|~VPyYQeFLtkXw8B`kspcA8_GiB#Vs(z zxY9JJR#KmyJ-Mfe&oZ?d$%6Y11B~Pg!$f=WEVI`+Eswvbh&ow$Ia%jeo0>Ka`uhHY z*T*%&<5Vf3o5mQbjZ&?&x6Za8^z!XbEm7r)H{gu8gh@>_%au(d%UHx=7jLTr^eocL z(^GqQtyWySDpzn#Gb)?eTAYeED0Y1$Cf-b2aqd%6?a<+MYB(Q*R+!*;TUt%3GMhH7 zIn=6Vfmf~7D%C?ibRQE`=UF-j3$Xkby>PmI!fz1vZcBL2Z@tJDw(y3nwj1$gAKh zcu25_IiEmD208r z0vy#ofcaNh>>h|qmH-=cv;i=aJErg`$n#=%yvHqBh zWJ*%qw_vXYF{f5jYlahsR*Sh0kJ-Ck@*gj|H-aECnkp!wzr^w1xTGN}c2pDltNCbU ztQex+sO*`kR$6T|NunUa60veWlQ!e*9Xhv`ahl6S&Yn9b2qZnQF#(gQ+f*F3`kYV3 zGi*^8>P-{kJ+{!>FIfVRS|wCAVN6>-@Uj`gAnUNArrVV&0z-?AMa$KHo@w>j&rO?c zm)o`WTZy0cm=1c`skR$V!w#_v_epOyWAiJIzqKA8isQAyN&hrHdE z&I?rbog5uC=55%6TLAm<&$u2_DeXeIhGnn?FdoepwA8iwVc~MIRbQgV$sR!ZH3+q= zYdRmQTO~iRM$9Se2fPC$t~VersSUdT$>m<%I9(tTF1XXG4#614vs8;3JH zfLO89-zKjYmNAv>ZKPUCmKK{a?5UBe{ zfdIc`M#=F97JwhoPP*Sq;*J`O%ta7oXGpQP9_n}uWy=C7?HOUS-82B0B%>U0M4JxZ z?-2}sh$_b|5iio`dW7vDdU%Du)Q*{-%EvFH6jz6|StjH0jKTaoGi23U5HA~8%0wVU zm}Iu*uqLo}ooKq_p}MwSf1!U^;tIy9FODC^JuTPpLkLeZ*KDQdO+5 zfL5{gf7*GhI;(KvKV3W+0tAE~7-&xh+|?%p2>;W|(Z9_*&5X81Dikql@>QwOwP2x> zP)V$eMQn$`MGM=kGLp%s7}mE@|H5W>d(~qxCRiHteH6twwAx^3s~i?Q>~z1(`0V;W zlAXv%R-=E%CwHo|aJX>)XKj=dGUkwrzvBu6~8IR{My1AMNwuLr|e&yzV=l* zGwv-qs^N0!QW>5>>;xC^bMMa85klAPfv#Y@%?f5Oo^sE^<#9_Cqlsox2B$NC`tQ6Y z*Ah(~y08X)Yi7Pn02&)}oGaeG(PNk;Zs~i@04l#ou*3l*zZQZnjBJNB7-M+rTB+RETS+o1MB9JvXnsd@RX|AAmj1ItXUW-uX|%4#EZHSn+?y{1T z@@jMBCFzLeJ#r#x3xe4q_vSuwisz&6kso$pzQanEPLQ9$>Jv7|--UqG;qUXWM7U&= zMH!hW*NSom?pc-0yXtxd)5RZ~_8d>Q{>TZErb#dJ1&t^9gf}PE>6a&IL_;SMLBY8v zOc3`@u&<98OMiv=@2=aFX_WK>!?jJ2M4gr4X3k-CC({!hW%wgFr3<~I zb=Gi**0g z*Ec)tU zQ^lb+$w*r@;F7mG)~1GfRjTwgS9&`ro#Zg&a zMuKizz zY?OXmNq$OA?}|fjS&kieNB^7Xl*NCyV8}ZLK<9%ySMN1Pt z^;J~)GuQ4H@VEcPA$Fx9t_Artl_yFQtbh0^d3W)iS$E-{8luGNj_M$Lxq8zgftyGh z;E8++fY6tA3k6ZvgtXJ&;nn*xB{@K}e&uk`9R%koYxpG+rAJMQvTFCI0ZPJ6ZD8{i zjS+ykmY`(8Wv#2Q;T_|Ps*x3WMv$F$TO0JE`D$?68`1|`K0>250QH*HuSV3Q0q08B z;5Kcdtp~E&T}?N~IIj0_2 zR#rLxF*=CW$$b##-RXVqmLWKVtQ|du;&@RQg-4Niv5S3ko)TLg!UQKNX%gr#+1&(BO6mwxq zn}W~MZmco)@Hb#~M~53pn66d8Jl4X*z=t{BRM`QU=8NpAIIsIS;#NvnF{BLkMm9L~ zrDT2ZV{uFPVV4~|&CtV)9Eq0D0%nfE^`3iUJ6w4XM1EnEI$3OlO{S;`0F9tfWD9$| zP)aSea6%nYv|K=49ifhjMPIxJ#BVf}Zi|XDk1au&p1CRvS^?+y<4`;E=%mB2JVt(4tLxUfCx=@hbx$!9GgVgM#0RXA(8**FA-FQq$dTVCQn?w1FgrX z({8-#hZYNm`FKXd09!P!06b8<@NsY4HYHi@K`T}H!px@`!<>FH^;zRDCSH%BinmIQ zyQdL2F*nFcDW5;+28#K=Zj-U8&To^03ioNfC}_*F?~FOZ1+$O)0L&)E?P>VZzc9@% z$EANCYo7Vkbmp(B-+t3^ylZnlz1imFFR;fdc=xA?##`9?TTy_fVZ`;rZ=?BSnLBb< z)sXDL3OB8$e8tXK{m%Y8Gw4mW*SRV4vJrrG9qU!*oJKJCMi6I%TG2 z*bDK5Q;2B03-p8{it@N4x+5Gp@SEG$JNiCMZW>C)C}{`FazsN+xB6mVAij|*PF8I@E6|n?2Xz$xs<`%DzHX{QOUfvrD zH4+4?f{a8X7f7g@9;DL)Yhnprq%X+ChY)^8%{VdHfH3BWVd@*!n}=|>YdA)AA?pa| zr-U=={q7I-sj$iX$wT({|F;J#Oe!39KKyQF#U}^ zXP3pjR{UDfbDH~*eY)kNzv0l==L@0O-x`8$PX2hWfpj7^EsI?L(+EYDgfLn&HR0%k zEH^^)_?8`|GQtf-0jF~XfG~B-fql^NNf@lyjN}^D+h}yo8~fgS-M#!QzX+dvRcU^0 z6*urwpnSW7#~|wcGR|sSWw{#9Ci!3+F3g~ndW|kWR-3tVHW9=yDZg`7FNOKB~jasmG7+sn^v9o`epZd2@hhnf!Y{Fs3W%t2}Jhe}$9 z?Mh*TfVq*9XowUO>_4hJ)^}&E`HRc0jL;&%8+lW0&BEfR^jXB@E*^Le(f&!5r0mQH;U~0iWz#X=RO+!j9hxj=% z1RL^vdnDzOH%uxO3?$46&lj{ptl&YCM0UQD&oAngJH+D>K637?GoYPysZ<+nHu31= zdL3mSeNmcKoAE&G6D;_WvhgyF$c@?%vB>!x@%o)oYm`5!{Zw>o4ExRe-1v|T=A52q zJNVYMZbGCRASEwvkZ%!|t1?bWP{&0Gk~N^5{?qwH7DzU-xMzZnTDOP`=Q7H3N{0rL z83IExoyZ^89iKPY+&8<2S%a25hMqzqn&Br#yC}U#^+<|WLX;eY5%c|jR0pX2p`rbM z(%=3c<}3J*>geEX!D!)ZWNK>$jI+0g72F$L9gM}}>}+jM9W+miDxAxE-$f?Ck&_-IFJ3t?K?&|V-)iqdE-W%LjHN|=Mj_Tc274cOj71lul z<#}e4Bf4#R9+829jphBtvI?D!-!T{1>h@=#9+sUz+FIzT9KYn#(%i~&B^5?=?8crQ z&g=wU0I8PJI9HgYgm5!T?rilqFG&U`mK4NftpK8 zVZ+_IBD=^!K5;T#!uq$q)&D#F)3Kbys`z~rvfiu-dB`JRNf`>B8hvHkXo={V=t*~%|!?&$P%ShJk108pRD zIIV}^1Yds(ml7V{%g9u?FY8;fZ{y|uH=0Im$k*FR%T!kZ-370^CzN~B@CK~ufs>(0 zGWJDTc>LA?8MCwWMU7Fmd11;U?>!e4$;-O`zI0Rc6%5OWUwBA{Hpn4!Ai2rWkZxmvO`vkedw7FNPXGYaBk98IWx3si(Gk$~d zE*4jRU#QPpIA=t;D$W{}f6KxyMX36>z_fw&U{m}XYu79{O^arntTFA?A$GA}Q10$R z9LT9nWSJuB+&sr$^s6dpGXK$3fEqY0A$vz$LeRz7>O#RDv-=V>?G{mn%x6&l9#1nz zao*>{s)Cq}WYnQ>2-h{KKfK!@+18p7q? zns@LymlCUFOMm8VfIAB(vq^GI`bhguy_e!0KY8Ts(wY!k1VD*k3I?D4m~WPbl+ z^3k2Zep!voH}}8epq9`&@Hv95}np1`i;@}SUw@w^i4j!ko`)F^Bdy71&pOt zGI(H&hZ8uUP_VS=hiAYK@PE;orcf_ysQ-8m0rNlpEh)=Y_2Wnbr-O7*Y@?&aHx4MH zFz5~3WuHcbB7pyJT<+g@d=Ov?%4_qopda4UI8+yoBSJI%Dqv9X6Q$0o^TrV=la%mx zt-Q(bI(o$56x_-8JvafOk(V@REH?{ zwN}1vS?z}wC|z89c~b#yEVkw;?8nD<1wMG}afJD49wH-}q{Vx&eZR4gR9owtx9D8q zE2B`@OfD`jNxC(8CZOvNn_}yeWbcXd3w@!?(^ds%fAOSzj3Rv$|D$Vv=Tbc7;& zVA{020byM8X+d_+dNpPNS6U5_aEv31CmuOu@?tTqnPw$bzq%s9QlC7a@JbeDx8LV5 z&d^YO_@(+lZ~O?hnDPgS%=)oU$hr0YAe7rti6pkG9V=CeRDp0VAel;Rm~s4G3Z_*% zatpuyryTOWC{Mf*18nRQqA=2`elNo=??FIvjG_z*#;-!}`aW@__Qb9v0N+7jGydEh!q|0)q zLpp$^!ulhiQQf*F8ze|50U9as*0#wYEUd}_Rjn2JYM< zH9+Jh@@O4bjqXiA=TM&K3VDim9GFAGY;ON6K#ip`9`Z5 ztNiv>S`@{BU4<#zPLsgGrUk`}DoKSC@6zQ{shwTSrutS~X`xTG2uZ24g~xR-93Z_k z4{Mh|0e(1V#AUkJj(k(ud~(r~mn_#WrUfp8qD#(TSalt>#V*2KJqyTh4b#fzQC3~d zYGdQeyoAo~;>~7Nw(-uJuTh6{0~+k6?m=ROF>T{3z4BuQ%zSYY*aa4u&1ocJSlgCP zL5{z00olZw<(}a)9rmrtwlZ)045%@LZ4vi5Fs~GZ@#8$It92DHG4C!LFse6JAz5FV z2eNe;tBYFDZ6vI?s<7E}7iv^P&P|xprD9t~Ubl2EjKH-;LGrhmK}N)?RP#0kWd999rOPQJQOS zXDj9<_4`Mk87U?EX*-nZF1dEkKO^?H#@Sw;h=+12MfUL``MPtGq};V8aI8Z%j zSLukT)XdJ!fSeiT1C$hG3qm>=K0asqWSn4n&$IiTVqm+%H)7bEw-d0|cBRDu_&Tm1 zu4Kd#jcBV}p6e8bjn&Jd+I3{Q0#b;^LcqDPCOAAULD2^ITP!U^m8if9>T7IuP|wb8 zu2a+H7*U&l)kL)0TR|rH*TQS8L>bv^(I<_d#=ehZL{ZGCnY#iP?tG~$s! z*)2i%e6V7#bSZch7|bk`mXeGbbTyMp1TksVQqyMZ%R8WJ!F!gZ&g>$;O(}U;2JR}v z=`dlzg6#`*5IQsLS*snR-!#!|adHo_Qth<5v5v(+thvfrZo^4bpKuJcG!*qA-gU%0j|lY9O1Xkho^PqG@OGW|7}qa$G45^ zR@OIuz~F?Jy>~TV<4qv=hH)*IpABAsPU|GgVJ`lZJPT|B5)k@={RtunP5hvi+#8j! zsixLAuoqtZr?fM;ZWIabYjqxY)NBf}O2`@p*lF#Iny$mV!hnSz zFw5To0yWPFA*VAhq#bcJ600Wfl*dPm1m7>@HoeEz(|MxVqw$KJlXu28^EDZhvQ6%a zdbm3>+9$`LzDN_*(w~7Lzw7lw-RtBSuoX%hWfADgE8n%ek)_-hk$-nTvOJdj2e<9I zrF#|sGU393C8Z-yO}*@#cYrPRomc-rQDRoBgOB0VQ#Mz5NVH*lDiYfzXDCO@#h;$5dJ#GdbUt}5S$328$G zjOF~c&xMUs`_+G%kN7C_s$~xTFpKoGA<2a?>?oX0ZxDWbc$TVjNz%FQAa_U9ET@== zX2qKL4U~I)v5St{iqf@A*o7y%0bs@$yq&|-3#CpMl&^pyui!`fL4W4!x?(5ycqz2A%dp>>z{=T_<=txe|)ne1}t>nU2(CHa}EQqgW(h0Q5~fenAeCRt0EzI&nn1-lC>#EVs z{lcghY)MVj^*}iD$7DUxuuGVwy~_V@f?fBpi7z2a#eZI@cIlr+Tsc3~8ge+U? zF-OxJ!Z&nccM3``lfnkmH=|iI-1=85lBRS-%K@u z47s{)OBdl*-=5wuiM1l`)))Jv(SO1%wZ!fxs_xI3qxQT6^8%YfHK4BkO>-f^AhW4}fF3UeOuq87WFqvICsbA_05C3^UP z2fE@gwFR$ADHhXuAeQIMTXgYfjqlWn0LX>cbkNge_WU6*% zxhb7L+82O4yGJj)uas|@U4E(wnZHS;LS!mB@`Sc}`vrC%U*o&0q@>MB6)ihI&@$EY zMw8Tnm=cM#{a(+qT1>dPp>`;aAAGDZjhmrONI!cZP&UKbbpyEY6$9`Gy~TNG?)zYJ zA-}zT951s)`3YpoJ)q=$817>#`Ud9?Y|&&^7@q*t@LATpi21APStF+ZQm8(dk{(a< zm1V!$y~iD*+?d~jW!_H}HB0mZ==Yj%>N{%*sM`J0f7#T`9b7=$1<*>IyS87)P#E;w zOQ12)UB#yz(O)G544udsHKEv|qZS^_O)_!g$#E1kvWLr3;mf$J(>Pc~tU!q2`gts6 zJI(_TOeD%7rV*De8;;SU(&BfB5Y?Ln#IuMYXtGId4f0t=K9H?2beQ(x!Ux}>{ibOj zqZ5#w6`Lbx3iX7NgsnJbcNRCSQv3(XM$68&Bm@^lTeCH~OBlP%syvNCS}U$(Uhfj4 z9{lDMeY!v`*<$TPn+YK4<4rF+kV{oT9~l6Z?Q6`Fd6GNVvM#P1ggq!$o)bmu=-u#< z;!=UgGHfwP)xy#Y!s0o>g-iuj_!S%hWV`{zop4r9bjn9*Qb`7+!aK#M=k)IkJqnET zDDOWm9!Y-Qh3o!eyrX_(sVgD6^Y#w)IUC~>65Q80Q~PH4%I;I>+ea9v#gLncCVYW#0pLcs0x(Y@-U$~UFO72N=)U!X3C@u!V^`l4EY?u#rs|Gr_x%m>fnmJmRf zt{>>=z3{`T+ODheiV$?f!ptaeQpkU2gj1mpWbAg(lZ5M~b$bQU)e$$YV7JpHH;PvW zJdNY#ldZ6f))Ha5?y z9%s74H%L-?$>se+tG`_tQ3*?~pQCbJf4pwy7Um40i-(hn_tG}?b~*a>AsK$&Qq@?e zwK}I8)1yGpb*%AK3FwpxkS_tSCRAS>NK7Qd4@cUpV83u2zYyt*`ueXu7Nojksruq2 z_Q0C201#KZ3DS~{j{FeZU->*d{I8hp&wD+311(s+o0WST;XP=oweM7+m$Us(1$4SZ zGDA-c!*cgqDuiNNJ92rR2-qW=2kg6|5Iqlz*-f+YKZA)m{^ouUnKc30>hIilKl5sn z_)Da}!M+yESkr#ue0$USEL5n`wtL`9_K2cG34H7c+#ITYl>dQp=Jq=4Lx1^ODvPlq zUkF~SQ#hT04P*A^bu>8>AkcPNmn7H|kA3 z>W5u7@CuU`{%q2X`M64H)J^EBlW`s%IR6*yf0dg52sIjtR&mAuEMBPpS-h|Uof@fu zT0;ncniPP-k`VS--)gLzYcK-(@Ge}C5L|LWVFWXZqA1G(xE`nya8uo)r7N?Rsuz4W z8X#4eWO)F0D~^+Q@u%Fj*ia6*^T7AAb?TMdb-Iz)*ZT#cIGhBD0mNNQ|3faV!CXTe zsf9psqKd9I&1za{Uo;?IV+t2-)O_Ua)^rWH%QVSQ8{;5ysFfA&koR&KL3`e?%$ zr99j&n}nahXp^|jW~+AKq)B~A*T8RtPu-&NnA~bAA;blK%XUp9^gIlC8wced|*UX&z?S1w>bMBdQ?mqkbp7^8JgMjSbmlX+a>*AP# z`@xnyWMlB;i@nfuTeGU&Na-o-Ujr6Rrp^Zkx$$~tHh`{Kf>^O^GoXpgOd70$q3e@& zGOr!wZoOgM?o72%sCd95n|NdExTFe4<6~Lfs*XyK8kE5t`!s9I-H$O${XG;ktv}yy zNgzW0D0b>OaH4PKY3TWyH^##98Q3OuOLVMj_$~fs-+qp1#Z_2nMEz=e!5l$~3vb2L z?(P{4kB9Btz0ZtVia~9u_WdWciINIBc*HZd*4vCbQubIeu<+_)Yqp#gvfF;zup!$4R$*n+A&%m-CNsxs!Csv$YGpk^m}HdJ_4^v1+4Y+;(~?W)Q~F!9VDQgJTcEGY0#5FH4U z%D{tGfRpP=*VTyC;p{uf)x-xx@|H0X@y{^PpI?P~ajDg}4DDJTYX{uAQe}vJ^_L$#K4Q+2pa8C3c$aVY_kqinbk~S9R|h2dlmH103T-1<|*;xe(msU|$@pflj>_ z##(NgnP9#B`*68XCcJcDQ=R0mcvJ4v^pB6A#G>XN5%g;fjD4s5#$FOECXiINlkBfU ziS-~Ip>~J>uuLrbUE9)Z)$@jczB&b#_TdFC8c~K=Sh3wSCiyYWOr>sUr(w1&hEPga zj(W?-bXvi(M;(;q&QsvNlJhdsQ;OUkN}3QaEzuYjl$iqRcdniFgVGg8q~FQel7C=A z^%>jOIDEPRq0?mJzEZDBG8I-QT6y&$q#!IZI3MuPZvnSU_K92ea@{KP)G0}c^N$Oe zg{Rx$IWNEKr4r#&8$!1FAx5cv_d+f3k5m=lMAT|Vk3f6eKLeKBD7{{TvoJK)!0rmhHf80Z51CkvGzK9)-WzWx}UQKY|6I)-vn|u9A}%0 zJ#KKWkny~r-cspFw=X$AYNXec=2mMLk|D}>OGqKoEfC`J=sMm|WSuQwRrwm{8=Yq? zB|nfUd0RYgR2x%m?BW4q4?oBPtNK9?X#I#9)aynamu=UT$3nr}UpN;&7ZAq>t#o>- z#GWE0yMcWdDmx<;%HD}GAYc;vIbsTI%!hY3TXudTSN~i7 z5aZT@#Tv2b0t%(9lN9>nI0-`B9?lUOMz>KkTS6DF*vt?2;d&CNXcO+}oh>o95<(-z z8|S*ByPpVH*`}($AIJQlY}y^tdN<+r!fv41^H9^;POYn3H;3S#O$v-vw*dfpAZ#~F z4!U4SsX%jOVYxmW<=q&wi}Ax{-v*F zFMF+};zvRxjbz}--u|A}o>Q{m`(EMo)Jy^Ijo~cu_KOw)?~{>s=ugxRk^qhsAR)tI z(rDCNtBR^oZ)Avm>A{MB>uFnfVu%3~6LcPqLHMz1EEKP5CbXroFXKWcfC(N}MknPW zhexv?)S2PD%f!XdmCtUeB%hpPV=y7)9}A}?2ixLr#6%B_#!q@a$**iLOZQIPp|Y1% zVJ!RnkwkaR%8>0-OL`A)mf!~`PDl2%ObWHlTBCruYISDkiZn%YA!qfvjhLT-3eXYP zhNIA@_f@AdAzK3_eTrdkeN6>CLnq?LK4-hX?skvNj>&h@ov5*%{mKW{a#k2DCJ${x z_b`~9G<#WQFSj&SjRvE`Q~ClokTKPL5asH|U~;JO3bNmGV(r{$Dml^|9bG!-`CVJK z!AU`rD7Spg2fIEwii^Xy+D_fx7!0kV?wHs&^`0?uDcEQ?EM^h2ELqRr`JPO-c1S) ze|drfK95ZC^~e`)O4|MaUARze2t1M3z89fPjwVpHIPN3dm+_X1Xg(#nX3J`;^pwL2 zpUeihf?&Gn1)a!CB*u5OMMI?CbiMXJ2ks?U?hrmA@OAkaaYr{4%~W2d7lkH*bwISc zkY7qJ)1@DW{M8yZdjA>WOPc`biwfVPm}pjRzRVJO*vC4YyJF;>L{7lvC_njKFIV)1@X){73fWMZ`E$D*LSqTt^)r=k-3JOJT- z|LAr_lg5$t4vQE+%^7tYRQ<{b^Vej-eOcuse52Up(Q2yv93xrRwHd_bq{)*p+Zi#3 zi}y#q81VZursP2rQ5K0OUt}<*GTcnK_Qz!s_MRp&DN$YGlx1kr{nR6yve4I)ncfVs z>U#g$L9WG38mdjq#njL%_KR>o9NnXcn2c{gE?fO82U8A-Sa61SX!Q?9lh`Yn zKeSXbb6QlP=Z(DZ#oiNj-+p*=P^-zxy@iV0&>nKc5TAzlQ!YX5Z2LDQ109BV;sGtw z-*F+-#+M{x#U3=MtUuG1cF5;)vS&**xyY#({wPR4bz4s73T)9+Hdx-&a(2Kf6$HJ^ ziO{zqqU{LdAI>+;L#e4dz^f7P*vMQNo?k#rGp`WSOg}2jd956J##aS;Khg~No|i^a zd7{;@6MtY!H6-W@4$ciGl*`?%HG$5%B&yF@q;iVq8rxwlRz}M%@MFJha*gTTp#8uu zH|g)voc01`i^i-_OZhn6K4TFa8a89$QyEY`fIs6&G3lg(?loJMPM^J>t`Hwzt-EQE zgsuDIDKEpEjk2`gc3SMagLLeNWvgy44`=J0DJ>^f%N_Au#3~0rSls z(nGxWSUIP5c|T-DAMFR&S(rd8IK=FxlQqQTLND7h^Mn0?7O9x#I}fUAn)xOqDZa^% zmJ0xn6xZOCn)~bxv%L?Ki)S^b3N-{azc;Tmr}dyUH|nx9M!Ks!yiDQnAFr9&)fJbV zw&vyLmwBulvzSF6JwSq?!`5_6jL9hLFDMI>R5DM)hg7o#deJ_xeMkTuKf1UBJ#>_* zOSGNPngJ$oM)5`FvndH#^W4f}DJEbTRs)@;8TO|X6-iy7#p8k7SU;Pr`}^dAvst;< zu-3`TEju@7y0kF#$E6t`=*d~nh{!L|2Lfyi{rKgw`W6{|pPiNOmC&}NmsndUbQ={b zHB3%%oj22)?M*&dy=5$%l}L0PC`OApX1w9b#n8?#_8F6a#guL_!#Y0lC;H9)%+#oJ zDS-k27^A{o7x6+9z-nE*#G#sx8k*0A+7C>+4aUC2kbMR9YY}5%aV^?91IeA)jqhDL zo1dXxYFj4DvT;8@DR}RD)TW8cBHjLQ3E+y|CrtIpHM}F%LyAR~!8Ow&a`TfKU*Td6 z(=AP%)t0)|L2FgZZN@FhfZoq?)tMtsqOzkng;_o5CJ)mBlPMGjJdgyl5Rd7m`1h{$7C!GT|)2eiZ9KD;tdk^Fmcko$_SpctT#k2w}z2o+ON* z$j3Qxt|{GisQ&6CJk>t>Y7`2wos}7^{ZS_HbNp(IcI9|}0ThhstH7f; zJIR(pf*eX)*v&a}gTU#6cPoz>sgArbxJ7E-(|sOtj#;@a;w1Q$WT^SAo`W?e$pigj zXZGabO|CZ`+x#Jhbr=QtW!nZ_+(H~&ub{v~oUYN*0Cjso!C)H+6-EDhxiIueNjp5Z z=8;ZbCkkfMs&A`SrXn~5-XO*KD#|EQ=fgT7uusutQJzDjwtAA2nn+2L%V4y~ckZQb zc!iNZH#kN5hgZRKmiYOgmirT{ZT2Ng9nO7>)H)=le7J*m$zVjSsI|s;rRGulrai zJ>gDnpRZ7@*chJS5nueical@il?N&vl@yll5OroA8jSU_h@aDs#{TCs)R+_V<)_6` zoUNvkTVZjO?&}ej_7|AcwY<<{Y>m?aaWEcY?{|0Qq9MVTQyrDa5{DQ?K>?+duV%ET zzP&M1wcky?6db0KjRc~zBS=afiO#7^3?+*Ai>vzst25!&(!hH8xa^?7FTbFZYDuSB ze)k+b+tbmP9?6nq>eQ6San8_4?9rC%wU~tYe_KEJ6&S|=VEq9X6V?U?vqo2cTgcm08 zBX$*Xo1@*lFp0kL6FQ-ZB^REqrpsNms+Fog>>@6R5T+d(?GFRgr{^amcaHQRsgMw8n2|uud-{3Z98lq=CGnRo>gOlsKNm z-~;+X^T%JB5oF&X+45<&>$Qc4X!-C=cI!Sj>TWd(V977^%SnA8vH0znab3KP@Xe^l zJg=+Ym=EV?WpCxLUj){{vi6*9K*?CWfJ;7H29-~CCnG&9DI!%~tM>)R{3=~6S5W&p5*t6UzP=T-^Dy(>k$j{6((^1Ez0UGg{D!zx9wyUjQWo_aql@}Uno$$cFK|a z^iY9<|Z7k#QIK09aJfA3ZjXip%$fagD zq>LqGx!C+OKkqFI&pBKB6b1=RY(%2(RtJJQNb@iMnq*=;z1JWPv#(ZxY7lAT|I#ou z`oyh;kG~h5bf3owo56yBOTYX@FbUyhLt-6wBDfmdZMcsTfcHSKh^ZHPS1J+@l38Q= z+Q=^`?rifzW}4ViT3S|`Wc#mx3tYNL8-k%YO8ba#yCBX4r_m^S34C78W%}vpNPOPA z%kj_L2+SXZ;~&U(=%ToVLjAtRB%dmQ{1QUbl4=U7<8{{`XuybiPwI0YGYNsgIv-jc zdi(v%CWIV=A;(cU>ypZm8KvDkaqC#cR92jVwM0 zl-XL@<*)5~Xj&qcpXST)uEqSBb=;#TU?Czg=2wRA9r8+E{;F|h)qpOmh}`C^B46H)9}R_a5C+(h?3;BG7odGmPVJ$R^R9E^jn;o+t*|s6Bl$C$aErY# z!4*}c$qHMqMV}{?2X)CsATvG3g?-Vzf%H7V64a(;Iz zYZlGFHPr55aE&e+PJEy^wE6Q5LCJUy1;v}C?GIqJ!S~n$xUVRng|{c+##5GCTr`Bm z-_?bzsI$08F^zJypRm`S+Qy`)+4Zf8={g<_PYZr=P`C&Tg6lSQa-@+JEMBRCwyyzyPoXd$0%iBJt%wr#uxA4Qp`wcnG)C>t{C+tBVy*sn(O zOelqUTEBeTi2I2Os(v?tZ$5X9Y7)=xS(u%~K4v-3en?yH@C(|ahrlcOIr@+~I(v#+ z-vBWeVffRH3-qmyaQuk8{rGD8t4~S7xc$jv1Lm)v=daju)Qh8R=305LHb&97KleBd z_s||CICG)Z}4HI!S#sDJ2+uOa_RVE=;$0Inrk|B?8e4f6jAA~L1{{|H}8ZeDXla{OJB zU9k0|HwfSq;$%de{~mck6flBDTG&zp5%skXFHMhQNf9QwA{>za7le4vgW)ymBN2ZH zkpTdP8;GDr0VLuNFEZkJ^bN#VBM2sXhYn`c2&B8N&8i}(*#c1;K4Ou~^}mrp_1G|Y z0|`t6mjc$_1pM9TBTb;&c|j1|>njP(Y`+V+ny(8JiI8yfX4>DSLCDfW3S?;{H4d!3 z`Clc-D|GBgB`tT6X22Eb2ILUGN*yTxz3;tE8!oyqm@=-#Fc(M*fRrW7|lB%-Szh5|HzFH6(HC| z|2y)6O!Q%@@9rW&*QNjVNxc6c*FDS302cR-8VUMC8w3FG{RcvHlb|RA*w8y^*8;qo# z0jYJ15$8||;g%Xg^G$?Aq$l10syo2w zI~0(hzmvHB#pMNgIwQ3ecd#RYe^R#qfV=;q5bt?G)vibz@!%jN@H(rY5aCS0|LFwA zUI-u?%oR@kyM^Q7*DY+|11p0IB1NNQgq*G?me>fNUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index 2f511035..b357ae06 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -7,6 +7,7 @@ import mapwriter.region.MwChunk; import mapwriter.tasks.SaveChunkTask; import mapwriter.tasks.UpdateSurfaceChunksTask; +import mapwriter.util.Config; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; @@ -96,7 +97,7 @@ public void updateUndergroundChunks() { } public void updateSurfaceChunks() { - int chunksToUpdate = Math.min(this.chunkMap.size(), this.mw.chunksPerTick); + int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; for (int i = 0; i < chunksToUpdate; i++) { Map.Entry entry = this.chunkMap.getNextEntry(); @@ -106,7 +107,7 @@ public void updateSurfaceChunks() { Chunk chunk = entry.getKey(); int flags = entry.getValue(); - if (MwUtil.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= this.mw.maxChunkSaveDistSq) { + if (MwUtil.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { flags |= (VISIBLE_FLAG | VIEWED_FLAG); } else { flags &= ~VISIBLE_FLAG; @@ -139,8 +140,8 @@ public void forceChunks(MwChunk[] chunkArray){ } private void addSaveChunkTask(Chunk chunk) { - if ((this.mw.multiplayer && this.mw.regionFileOutputEnabledMP) || - (!this.mw.multiplayer && this.mw.regionFileOutputEnabledSP)) { + if ((this.mw.multiplayer && Config.regionFileOutputEnabledMP) || + (!this.mw.multiplayer && Config.regionFileOutputEnabledSP)) { if (!chunk.isEmpty()) { this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); } diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 45338ea4..e93a063e 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -4,11 +4,11 @@ import java.util.ArrayList; import java.util.List; -import mapwriter.forge.MwConfig; import mapwriter.forge.MwForge; import mapwriter.forge.MwKeyHandler; import mapwriter.gui.MwGui; import mapwriter.gui.MwGuiMarkerDialog; +import mapwriter.handler.ConfigurationHandler; import mapwriter.map.MapTexture; import mapwriter.map.MapView; import mapwriter.map.Marker; @@ -20,106 +20,35 @@ import mapwriter.region.BlockColours; import mapwriter.region.RegionManager; import mapwriter.tasks.CloseRegionManagerTask; +import mapwriter.util.Config; +import mapwriter.util.Reference; +import mapwriter.util.Utils; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.util.ChatComponentText; -import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; - -/* - -data transfers ---------------- -chunk image (16x16 int[]) -> texture (512x512 GL texture) | every chunk update -region file png -> texture (512x512 GL texture) | on region load (slow, disk access) -texture (512x512 GL texture) -> region file png | on region unload (slow, disk access) -chunk (Chunk object) -> anvil save file | on chunk unload, separate thread handled by minecraft - -background thread ------------------- -performs all data transfers except Chunk->Anvil, which is handled by ThreadedFileIOBase in minecraft. -regions created in main thread when necessary, but filled from the background thread. - -initialization --------------- -init() - Called once only. - - registers event and key handlers - - loads configuration - - inits marker manager - - inits commands - - inits chunkQueue - -onClientLoggedIn() - Called upon entry to each world. - - inits executor - - inits overlay - - inits anvil save handler - - inits regionMap - -onConnectionClosed() - Called on every exit from world. - - closes chunkLoader - - closes regionMap - - closes overlay - - saves markermanager - - saves config - - closes executor - - flush chunkQueue - -Every hook and event handler should be enclosed in an 'if (this.ready)' statement to ensure that all -components are initialised. -One exception is the fillChunk handler which adds chunks to the chunkQueue so that they can be processed -after initialization. This is so that no chunks are skipped if the chunks are loaded before the player is -logged in. - -*/ +import net.minecraftforge.common.config.Configuration; public class Mw { public Minecraft mc = null; + // configuration files (global and world specific) + public static Configuration worldConfig = null; + // server information public String worldName = "default"; private String serverName = "default"; private int serverPort = 0; - // configuration files (global and world specific) - public MwConfig config; - public MwConfig worldConfig = null; - // directories private final File configDir; private final File saveDir; public File worldDir = null; public File imageDir = null; - // configuration options - public boolean linearTextureScalingEnabled = true; - public int coordsMode = 0; - public boolean undergroundMode = false; - public boolean teleportEnabled = true; - public String teleportCommand = "tp"; - public int defaultTeleportHeight = 80; - public int maxZoom = 5; - public int minZoom = -5; - public boolean useSavedBlockColours = false; - public int maxChunkSaveDistSq = 128 * 128; - public boolean mapPixelSnapEnabled = true; - public int textureSize = 2048; - public int configTextureSize = 2048; - public int maxDeathMarkers = 3; - public int chunksPerTick = 5; - public boolean portNumberInWorldNameEnabled = true; - public String saveDirOverride = ""; - public boolean regionFileOutputEnabledSP = true; - public boolean regionFileOutputEnabledMP = true; - public int backgroundTextureMode = 0; - //public boolean lightingEnabled = false; - // flags and counters public boolean ready = false; public boolean multiplayer = false; @@ -142,7 +71,6 @@ public class Mw { // constants public final static String catWorld = "world"; public final static String catMarkers = "markers"; - public final static String catOptions = "options"; public final static String worldDirConfigName = "mapwriter.cfg"; public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; @@ -160,13 +88,10 @@ public class Mw { public static Mw instance; - public Mw(MwConfig config) { + public Mw() { // client only initialization this.mc = Minecraft.getMinecraft(); - // load config - this.config = config; - // create base save directory this.saveDir = new File(this.mc.mcDataDir, "saves"); this.configDir = new File(this.mc.mcDataDir, "config"); @@ -177,13 +102,13 @@ public Mw(MwConfig config) { instance = this; - this.loadConfig(); + ConfigurationHandler.loadConfig(); } public String getWorldName() { String worldName; if (this.multiplayer) { - if (this.portNumberInWorldNameEnabled) { + if (Config.portNumberInWorldNameEnabled) { worldName = String.format("%s_%d", this.serverName, this.serverPort); } else { worldName = String.format("%s", this.serverName); @@ -208,79 +133,37 @@ public String getWorldName() { return worldName; } - public void loadConfig() { - this.config.load(); - this.linearTextureScalingEnabled = this.config.getOrSetBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); - this.useSavedBlockColours = this.config.getOrSetBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); - this.teleportEnabled = this.config.getOrSetBoolean(catOptions, "teleportEnabled", this.teleportEnabled); - this.teleportCommand = this.config.get(catOptions, "teleportCommand", this.teleportCommand).getString(); - this.coordsMode = this.config.getOrSetInt(catOptions, "coordsMode", this.coordsMode, 0, 2); - this.maxChunkSaveDistSq = this.config.getOrSetInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq, 1, 256 * 256); - this.mapPixelSnapEnabled = this.config.getOrSetBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); - this.maxDeathMarkers = this.config.getOrSetInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers, 0, 1000); - this.chunksPerTick = this.config.getOrSetInt(catOptions, "chunksPerTick", this.chunksPerTick, 1, 500); - this.saveDirOverride = this.config.get(catOptions, "saveDirOverride", this.saveDirOverride).getString(); - this.portNumberInWorldNameEnabled = config.getOrSetBoolean(catOptions, "portNumberInWorldNameEnabled", this.portNumberInWorldNameEnabled); - this.undergroundMode = this.config.getOrSetBoolean(catOptions, "undergroundMode", this.undergroundMode); - this.regionFileOutputEnabledSP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledSP", this.regionFileOutputEnabledSP); - this.regionFileOutputEnabledMP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledMP", this.regionFileOutputEnabledMP); - this.backgroundTextureMode = this.config.getOrSetInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode, 0, 1); - //this.lightingEnabled = this.config.getOrSetBoolean(catOptions, "lightingEnabled", this.lightingEnabled); - - this.maxZoom = this.config.getOrSetInt(catOptions, "zoomOutLevels", this.maxZoom, 1, 256); - this.minZoom = -this.config.getOrSetInt(catOptions, "zoomInLevels", -this.minZoom, 1, 256); - - this.configTextureSize = this.config.getOrSetInt(catOptions, "textureSize", this.configTextureSize, 1024, 8192); - this.setTextureSize(); - } - public void loadWorldConfig() { // load world specific config file File worldConfigFile = new File(this.worldDir, worldDirConfigName); - this.worldConfig = new MwConfig(worldConfigFile); + this.worldConfig = new Configuration(worldConfigFile); this.worldConfig.load(); this.dimensionList.clear(); - this.worldConfig.getIntList(catWorld, "dimensionList", this.dimensionList); + this.worldConfig.get(catWorld, "dimensionList", Utils.integerListToIntArray(this.dimensionList)); this.addDimension(0); this.cleanDimensionList(); } - public void saveConfig() { - this.config.setBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); - this.config.setBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); - this.config.setInt(catOptions, "textureSize", this.configTextureSize); - this.config.setInt(catOptions, "coordsMode", this.coordsMode); - this.config.setInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq); - this.config.setBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); - this.config.setInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers); - this.config.setInt(catOptions, "chunksPerTick", this.chunksPerTick); - this.config.setBoolean(catOptions, "undergroundMode", this.undergroundMode); - this.config.setInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode); - //this.config.setBoolean(catOptions, "lightingEnabled", this.lightingEnabled); - - this.config.save(); - } - public void saveWorldConfig() { - this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); + //this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); this.worldConfig.save(); } public void setTextureSize() { - if (this.configTextureSize != this.textureSize) { + if (Config.configTextureSize != Config.textureSize) { int maxTextureSize = Render.getMaxTextureSize(); int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= this.configTextureSize)) { + while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { textureSize *= 2; } textureSize /= 2; MwUtil.log("GL reported max texture size = %d", maxTextureSize); - MwUtil.log("texture size from config = %d", this.configTextureSize); + MwUtil.log("texture size from config = %d", Config.configTextureSize); MwUtil.log("setting map texture size to = %d", textureSize); - this.textureSize = textureSize; + Config.textureSize = textureSize; if (this.ready) { // if we are already up and running need to close and reinitialize the map texture and // region manager. @@ -337,15 +220,15 @@ public void toggleMarkerMode() { // cheap and lazy way to teleport... public void teleportTo(int x, int y, int z) { - if (this.teleportEnabled) { - this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", this.teleportCommand, x, y, z)); + if (Config.teleportEnabled) { + this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); } else { MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); } } public void warpTo(String name) { - if (this.teleportEnabled) { + if (Config.teleportEnabled) { //MwUtil.printBoth(String.format("warping to %s", name)); this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); } else { @@ -354,7 +237,7 @@ public void warpTo(String name) { } public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!this.teleportCommand.equals("warp")) { + if (!Config.teleportCommand.equals("warp")) { double scale = mapView.getDimensionScaling(this.playerDimension); this.teleportTo((int) (x / scale), y, (int) (z / scale)); } else { @@ -363,7 +246,7 @@ public void teleportToMapPos(MapView mapView, int x, int y, int z) { } public void teleportToMarker(Marker marker) { - if (this.teleportCommand.equals("warp")) { + if (Config.teleportCommand.equals("warp")) { this.warpTo(marker.name); } else if (marker.dimension == this.playerDimension) { this.teleportTo(marker.x, marker.y, marker.z); @@ -397,7 +280,7 @@ public void saveBlockColours(BlockColours bc) { public void reloadBlockColours() { BlockColours bc = new BlockColours(); File f = new File(this.configDir, blockColourSaveFileName); - if (this.useSavedBlockColours && f.isFile()) { + if (Config.useSavedBlockColours && f.isFile()) { // load block colours from file MwUtil.logInfo("loading block colours from %s", f); bc.loadFromFile(f); @@ -419,16 +302,16 @@ public void reloadMapTexture() { this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); this.executor.close(); MapTexture oldMapTexture = this.mapTexture; - MapTexture newMapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); + MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); this.mapTexture = newMapTexture; if (oldMapTexture != null) { oldMapTexture.close(); } this.executor = new BackgroundExecutor(); - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); UndergroundTexture oldTexture = this.undergroundMapTexture; - UndergroundTexture newTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); + UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); this.undergroundMapTexture = newTexture; if (oldTexture != null) { this.undergroundMapTexture.close(); @@ -436,17 +319,17 @@ public void reloadMapTexture() { } public void setCoordsMode(int mode) { - this.coordsMode = Math.min(Math.max(0, mode), 2); + Config.coordsMode = Math.min(Math.max(0, mode), 2); } public int toggleCoords() { - this.setCoordsMode((this.coordsMode + 1) % 3); - return this.coordsMode; + this.setCoordsMode((Config.coordsMode + 1) % 3); + return Config.coordsMode; } public void toggleUndergroundMode() { - this.undergroundMode = !this.undergroundMode; - this.miniMap.view.setUndergroundMode(this.undergroundMode); + Config.undergroundMode = !Config.undergroundMode; + this.miniMap.view.setUndergroundMode(Config.undergroundMode); } public void setServerDetails(String hostname, int port) { @@ -478,12 +361,12 @@ public void load() { // get world and image directories File saveDir = this.saveDir; - if (this.saveDirOverride.length() > 0) { - File d = new File(this.saveDirOverride); + if (Config.saveDirOverride.length() > 0) { + File d = new File(Config.saveDirOverride); if (d.isDirectory()) { saveDir = d; } else { - MwUtil.log("error: no such directory %s", this.saveDirOverride); + MwUtil.log("error: no such directory %s", Config.saveDirOverride); } } @@ -512,17 +395,17 @@ public void load() { this.markerManager = new MarkerManager(); this.markerManager.load(this.worldConfig, catMarkers); - this.playerTrail = new Trail(this, "player"); + this.playerTrail = new Trail(this, Reference.PlayerTrailName); // executor does not depend on anything this.executor = new BackgroundExecutor(); // mapTexture depends on config being loaded - this.mapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); - this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); + this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); + this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); this.reloadBlockColours(); // region manager depends on config, mapTexture, and block colours - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); // overlay manager depends on mapTexture this.miniMap = new MiniMap(this); this.miniMap.view.setDimension(this.mc.thePlayer.dimension); @@ -571,7 +454,7 @@ public void close() { this.mapTexture.close(); this.saveWorldConfig(); - this.saveConfig(); + //this.saveConfig(); this.tickCounter = 0; @@ -589,7 +472,7 @@ public void onTick() { this.updatePlayer(); - if (this.undergroundMode && ((this.tickCounter % 30) == 0)) { + if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { this.undergroundMapTexture.update(); } @@ -645,9 +528,9 @@ public void onChunkUnload(Chunk chunk) { // from onTick when mc.currentScreen is an instance of GuiGameOver // it's the only option to detect death client side public void onPlayerDeath(EntityPlayerMP player) { - if (this.ready && (this.maxDeathMarkers > 0)) { + if (this.ready && (Config.maxDeathMarkers > 0)) { this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - this.maxDeathMarkers + 1; + int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; for (int i = 0; i < deleteCount; i++) { // delete the first marker found in the group "playerDeaths". // as new markers are only ever appended to the marker list this will delete the diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 1bb22a1b..09316880 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -4,6 +4,7 @@ import mapwriter.Mw; import mapwriter.api.MwAPI; +import mapwriter.handler.ConfigurationHandler; import mapwriter.overlay.OverlayGrid; import mapwriter.overlay.OverlaySlime; import net.minecraftforge.common.MinecraftForge; @@ -11,14 +12,14 @@ public class ClientProxy extends CommonProxy { - private MwConfig config; - - public void preInit(File configFile) { - this.config = new MwConfig(configFile); + public void preInit(File configFile) + { + ConfigurationHandler.init(configFile); + FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); } public void load() { - Mw mw = new Mw(this.config); + Mw mw = new Mw(); MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); FMLCommonHandler.instance().bus().register(new MwKeyHandler()); } diff --git a/src/main/java/mapwriter/forge/MwConfig.java b/src/main/java/mapwriter/forge/MwConfig.java deleted file mode 100644 index 35673dbd..00000000 --- a/src/main/java/mapwriter/forge/MwConfig.java +++ /dev/null @@ -1,135 +0,0 @@ -package mapwriter.forge; - -import java.io.File; -import java.util.List; - -import mapwriter.MwUtil; -import net.minecraftforge.common.config.Configuration; - -public class MwConfig extends Configuration { - - public MwConfig(File file) { - super(file, true); - } - - public boolean getOrSetBoolean(String category, String key, boolean defaultValue) { - return this.get(category, key, defaultValue ? 1 : 0).getInt() != 0; - } - - public void setBoolean(String category, String key, boolean value) { - this.get(category, key, value).set(value ? 1 : 0); - } - - public int getOrSetInt(String category, String key, int defaultValue, int minValue, int maxValue) { - int value = this.get(category, key, defaultValue).getInt(); - return Math.min(Math.max(minValue, value), maxValue); - } - - public void setInt(String category, String key, int value) { - this.get(category, key, value).set(value); - } - - public long getColour(String category, String key) { - long value = -1; - if (this.hasKey(category, key)) { - try { - String valueString = this.get(category, key, "").getString(); - if (valueString.length() > 0) { - value = Long.parseLong(valueString, 16); - value &= 0xffffffffL; - } - } catch (NumberFormatException e) { - MwUtil.log("error: could not read colour from config file %s:%s", category, key); - value = -1; - } - } - return value; - } - - public int getColour(String category, String key, int value) { - long valueLong = this.getColour(category, key); - if (valueLong >= 0L) { - value = (int) (valueLong & 0xffffffffL); - } - return value; - } - - public int getOrSetColour(String category, String key, int value) { - long valueLong = this.getColour(category, key); - if (valueLong >= 0L) { - value = (int) (valueLong & 0xffffffffL); - } else { - this.setColour(category, key, value); - } - return value; - } - - public void setColour(String category, String key, int n) { - this.get(category, key, "00000000").set(String.format("%08x", n)); - } - - public void setColour(String category, String key, int n, String comment) { - this.get(category, key, "00000000", comment).set(String.format("%08x", n)); - } - - public String getSingleWord(String category, String key) { - String value = ""; - if (this.hasKey(category, key)) { - value = this.get(category, key, value).getString().trim(); - int firstSpace = value.indexOf(' '); - if (firstSpace >= 0) { - value = value.substring(0, firstSpace); - } - } - return value; - } - - public void setSingleWord(String category, String key, String value, String comment) { - if ((comment != null) && (comment.length() > 0)) { - value = value + " # " + comment; - } - this.get(category, key, value).set(value); - } - - public void getIntList(String category, String key, List list) { - // convert List of integers to integer array to pass as default value - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) { - array[i] = list.get(i); - } - - // get integer array from config file - int[] arrayFromConfig = null; - try { - arrayFromConfig = this.get(category, key, array).getIntList(); - } catch (Exception e) { - e.printStackTrace(); - arrayFromConfig = null; - } - if (arrayFromConfig != null) { - array = arrayFromConfig; - } - - // convert integer array back to List of integers - list.clear(); - for (int i = 0; i < array.length; i++) { - list.add(array[i]); - } - } - - public void setIntList(String category, String key, List list) { - // convert List of integers to integer array - int size = list.size(); - String[] array = new String[size]; - for (int i = 0; i < size; i++) { - array[i] = list.get(i).toString(); - } - // write integer array to config file - try { - this.get(category, key, array).set(array); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index 48c7e0d8..0e04f98a 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -2,13 +2,9 @@ import java.net.InetSocketAddress; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import mapwriter.Mw; +import mapwriter.util.Reference; import net.minecraft.client.Minecraft; -import net.minecraftforge.client.event.RenderGameOverlayEvent; -import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; @@ -21,16 +17,19 @@ import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; -@Mod(modid="MapWriter", name="MapWriter", version="2.2.3") +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +@Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS ) public class MwForge { - @Instance("MapWriter") + @Instance(Reference.MOD_ID) public static MwForge instance; - @SidedProxy(clientSide="mapwriter.forge.ClientProxy", serverSide="mapwriter.forge.CommonProxy") + @SidedProxy(clientSide=Reference.CLIENT_PROXY_CLASS, serverSide=Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; - public static Logger logger = LogManager.getLogger("MapWriter"); + public static Logger logger = LogManager.getLogger(Reference.MOD_ID); @EventHandler public void preInit(FMLPreInitializationEvent event) { diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java new file mode 100644 index 00000000..c56d3c09 --- /dev/null +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -0,0 +1,34 @@ +package mapwriter.gui; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.handler.ConfigurationHandler; +import mapwriter.util.Reference; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class ModGuiConfig extends GuiConfig +{ + public ModGuiConfig(GuiScreen guiScreen) + { + super(guiScreen, + new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + Reference.MOD_ID, + false, + false, + GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); + } + + private static List getConfigElements() + { + List list = new ArrayList(); + + return list; + } + +} diff --git a/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java new file mode 100644 index 00000000..048c4c8b --- /dev/null +++ b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java @@ -0,0 +1,37 @@ +package mapwriter.gui; + +import java.util.Set; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.fml.client.IModGuiFactory; + +public class ModGuiFactoryHandler implements IModGuiFactory +{ + + @Override + public void initialize(Minecraft minecraftInstance) { + // TODO Auto-generated method stub + + } + + @Override + public Class mainConfigGuiClass() { + // TODO Auto-generated method stub + return ModGuiConfig.class; + } + + @Override + public Set runtimeGuiCategories() { + // TODO Auto-generated method stub + return null; + } + + @Override + public RuntimeOptionGuiHandler getHandlerFor( + RuntimeOptionCategoryElement element) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index cc669138..8e533f03 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -15,6 +15,7 @@ import mapwriter.map.mapmode.MapMode; import mapwriter.tasks.MergeTask; import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Config; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.BlockPos; @@ -82,7 +83,7 @@ public boolean posWithin(int x, int y) { public MwGui(Mw mw) { this.mw = mw; - this.mapMode = new FullScreenMapMode(mw.config); + this.mapMode = new FullScreenMapMode(); this.mapView = new MapView(this.mw); this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); @@ -256,7 +257,7 @@ protected void keyTyped(char c, int key) { this.mw, this.mapView, this.mouseBlockX, - this.mw.defaultTeleportHeight, + Config.defaultTeleportHeight, this.mouseBlockZ ) ); @@ -299,7 +300,7 @@ protected void keyTyped(char c, int key) { this.mw.markerManager.update(); } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(this.mw.undergroundMode); + this.mapView.setUndergroundMode(Config.undergroundMode); } break; } @@ -389,7 +390,7 @@ protected void mouseClicked(int x, int y, int button) { } else { // marker at mouse pointer location mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY : this.mw.defaultTeleportHeight; + my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; mz = this.mouseBlockZ; } this.mc.displayGuiScreen( @@ -420,7 +421,7 @@ else if (button == 2) { // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB // not called on mouse movement. - protected void mouseMovedOrUp(int x, int y, int button) { + protected void mouseReleased(int x, int y, int button) { //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); if (button == 0) { this.mouseLeftHeld = 0; diff --git a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java index 0cf293ee..a769d4e5 100644 --- a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java +++ b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java @@ -1,6 +1,7 @@ package mapwriter.gui; import mapwriter.Mw; +import mapwriter.util.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; @@ -42,25 +43,25 @@ public class MwGuiOptionSlot extends GuiSlot { public void updateButtonLabel(int i) { switch(i) { case 0: - this.buttons[i].displayString = "Draw coords: " + coordsModeStringArray[this.mw.coordsMode]; + this.buttons[i].displayString = "Draw coords: " + coordsModeStringArray[Config.coordsMode]; break; case 1: this.buttons[i].displayString = "Circular mode: " + this.mw.miniMap.smallMapMode.circular; break; case 2: - this.buttons[i].displayString = "Texture size: " + this.mw.configTextureSize; + this.buttons[i].displayString = "Texture size: " + Config.configTextureSize; break; case 3: - this.buttons[i].displayString = "Texture scaling: " + (this.mw.linearTextureScalingEnabled ? "linear" : "nearest"); + this.buttons[i].displayString = "Texture scaling: " + (Config.linearTextureScalingEnabled ? "linear" : "nearest"); break; case 4: this.buttons[i].displayString = "Trail markers: " + (this.mw.playerTrail.enabled); break; case 5: - this.buttons[i].displayString = "Map colours: " + (this.mw.useSavedBlockColours ? "frozen" : "auto"); + this.buttons[i].displayString = "Map colours: " + (Config.useSavedBlockColours ? "frozen" : "auto"); break; case 6: - this.buttons[i].displayString = "Max draw distance: " + Math.round(Math.sqrt(this.mw.maxChunkSaveDistSq)); + this.buttons[i].displayString = "Max draw distance: " + Math.round(Math.sqrt(Config.maxChunkSaveDistSq)); break; case 7: this.buttons[i].displayString = "Mini map size: " + this.mw.miniMap.smallMapMode.heightPercent; @@ -69,13 +70,13 @@ public void updateButtonLabel(int i) { this.buttons[i].displayString = "Mini map position: " + miniMapPositionStringArray[this.miniMapPositionIndex]; break; case 9: - this.buttons[i].displayString = "Map pixel snapping: " + (this.mw.mapPixelSnapEnabled ? "enabled" : "disabled"); + this.buttons[i].displayString = "Map pixel snapping: " + (Config.mapPixelSnapEnabled ? "enabled" : "disabled"); break; case 10: - this.buttons[i].displayString = "Max death markers: " + this.mw.maxDeathMarkers; + this.buttons[i].displayString = "Max death markers: " + Config.maxDeathMarkers; break; case 11: - this.buttons[i].displayString = "Background mode: " + backgroundModeStringArray[this.mw.backgroundTextureMode]; + this.buttons[i].displayString = "Background mode: " + backgroundModeStringArray[Config.backgroundTextureMode]; break; //case 11: // this.buttons[i].displayString = "Map Lighting: " + (this.mw.lightingEnabled ? "enabled" : "disabled"); @@ -120,15 +121,15 @@ protected void elementClicked(int i, boolean doubleClicked, int x, int y) { break; case 2: // toggle texture size - this.mw.configTextureSize *= 2; - if (this.mw.configTextureSize > 4096) { - this.mw.configTextureSize = 1024; + Config.configTextureSize *= 2; + if (Config.configTextureSize > 4096) { + Config.configTextureSize = 1024; } break; case 3: // linear scaling - this.mw.linearTextureScalingEnabled = !this.mw.linearTextureScalingEnabled; - this.mw.mapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); + Config.linearTextureScalingEnabled = !Config.linearTextureScalingEnabled; + this.mw.mapTexture.setLinearScaling(Config.linearTextureScalingEnabled); //this.mw.undergroundMapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); break; case 4: @@ -137,19 +138,19 @@ protected void elementClicked(int i, boolean doubleClicked, int x, int y) { break; case 5: // map colours - this.mw.useSavedBlockColours = !this.mw.useSavedBlockColours; + Config.useSavedBlockColours = !Config.useSavedBlockColours; // reload block colours before saving in case player changed // texture packs before pressing button. this.mw.reloadBlockColours(); break; case 6: // toggle max chunk save dist - int d = Math.round((float) Math.sqrt(this.mw.maxChunkSaveDistSq)); + int d = Math.round((float) Math.sqrt(Config.maxChunkSaveDistSq)); d += 32; if (d > 256) { d = 64; } - this.mw.maxChunkSaveDistSq = d * d; + Config.maxChunkSaveDistSq = d * d; break; case 7: this.mw.miniMap.smallMapMode.toggleHeightPercent(); @@ -182,18 +183,18 @@ protected void elementClicked(int i, boolean doubleClicked, int x, int y) { } case 9: // map scroll pixel snapping - this.mw.mapPixelSnapEnabled = !this.mw.mapPixelSnapEnabled; + Config.mapPixelSnapEnabled = !Config.mapPixelSnapEnabled; break; case 10: // max death markers - this.mw.maxDeathMarkers++; - if (this.mw.maxDeathMarkers > 10) { - this.mw.maxDeathMarkers = 0; + Config.maxDeathMarkers++; + if (Config.maxDeathMarkers > 10) { + Config.maxDeathMarkers = 0; } break; case 11: // background texture mode - this.mw.backgroundTextureMode = (this.mw.backgroundTextureMode + 1) % 3; + Config.backgroundTextureMode = (Config.backgroundTextureMode + 1) % 3; break; //case 11: // // lighting diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index 8ad24534..41dda883 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -2,6 +2,7 @@ import mapwriter.Mw; import mapwriter.map.MapView; +import mapwriter.util.Config; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -28,7 +29,7 @@ public boolean submit() { int height = this.getInputAsInt(); if (this.inputValid) { height = Math.min(Math.max(0, height), 255); - this.mw.defaultTeleportHeight = height; + Config.defaultTeleportHeight = height; this.mw.teleportToMapPos(this.mapView, this.teleportX, height, this.teleportZ); done = true; } diff --git a/src/main/java/mapwriter/handler/ConfigurationHandler.java b/src/main/java/mapwriter/handler/ConfigurationHandler.java new file mode 100644 index 00000000..507f48d5 --- /dev/null +++ b/src/main/java/mapwriter/handler/ConfigurationHandler.java @@ -0,0 +1,84 @@ +package mapwriter.handler; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.util.Config; +import mapwriter.util.Reference; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.client.event.ConfigChangedEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + + public class ConfigurationHandler + { + public static Configuration configuration; + + public static void init(File configFile) + { + // Create the configuration object from the given configuration file + if (configuration == null) + { + configuration = new Configuration(configFile); + loadConfig(); + } + } + + public static void loadConfig() + { + configuration.load(); + Config.linearTextureScalingEnabled = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingEnabled, ""); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, ""); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, ""); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, ""); + Config.coordsMode = configuration.getInt("coordsMode", Reference.catOptions, Config.coordsMode, 0, 2, ""); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, ""); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, ""); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, ""); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, ""); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, ""); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, ""); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, ""); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, ""); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, ""); + Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, ""); + + Config.maxZoom = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.maxZoom, 1, 256, ""); + Config.minZoom = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.minZoom, 1, 256, ""); + + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 8192, ""); + + if (configuration.hasChanged()) + { + configuration.save(); + } + + //Mw.instance.setTextureSize(); + } + + public static void loadWorldConfig() + { + // load config file options + Config.modeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.modeIndex, 0, 1000, ""); + Config.zoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.minZoom, Config.maxZoom, ""); + } + + public static void SaveConfig() + { + //this.mw.config.setInt(Reference.catOptions, "overlayModeIndex", Config.modeIndex); + //this.mw.config.setInt(Reference.catOptions, "overlayZoomLevel", this.view.getZoomLevel()); + + //this.mw.config.setBoolean(Reference.catOptions, Reference.TrailName + "TrailEnabled", Config.PlayerTrailEnabled); + //this.mw.config.setInt(Reference.catOptions, Reference.TrailName + "TrailMaxLength", Config.maxLength); + //this.mw.config.setInt(Reference.catOptions, Reference.TrailName + "TrailMarkerIntervalMillis", (int) Config.intervalMillis); + } + + + @SubscribeEvent + public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) + { + if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) + { + loadConfig(); + } + } + } diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 40458fc2..583851f2 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -9,6 +9,7 @@ import mapwriter.api.IMwDataProvider; import mapwriter.api.MwAPI; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Config; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -36,7 +37,7 @@ public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { private void drawMap() { int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) this.mw.textureSize; + double tSize = (double) Config.textureSize; double zoomScale = (double) (1 << regionZoomLevel); // if the texture UV coordinates do not line up with the texture pixels then the texture @@ -48,7 +49,7 @@ private void drawMap() { // pixel boundaries when zoomed in. double u, v, w, h; - if ((!this.mapMode.circular) && (this.mw.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + if ((!this.mapMode.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; @@ -88,10 +89,10 @@ private void drawMap() { this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); // draw the background texture - if (this.mw.backgroundTextureMode > 0) { + if (Config.backgroundTextureMode > 0) { double bu1 = 0.0; double bu2 = 1.0; double bv1 = 0.0; double bv2 = 1.0; - if (this.mw.backgroundTextureMode == 2) { + if (Config.backgroundTextureMode == 2) { // background moves with map if mode is 2 double bSize = tSize / 256.0; bu1 = u * bSize; bu2 = (u + w) * bSize; @@ -213,11 +214,11 @@ private void drawCoords() { if (this.mapMode.coordsEnabled) { GL11.glPushMatrix(); GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (this.mw.coordsMode != 2) { + if (Config.coordsMode != 2) { GL11.glScalef(0.5f, 0.5f, 1.0f); } int offset = 0; - if (this.mw.coordsMode > 0) { + if (Config.coordsMode > 0) { Render.drawCentredString(0, 0, this.mapMode.textColour, "%d, %d, %d", this.mw.playerXInt, @@ -226,7 +227,7 @@ private void drawCoords() { ); offset += 12; } - if (this.mw.undergroundMode) { + if (Config.undergroundMode) { Render.drawCentredString( 0, offset, this.mapMode.textColour,"underground mode" ); @@ -259,7 +260,7 @@ public void draw() { this.mapMode.setScreenRes(); this.mapView.setMapWH(this.mapMode); - this.mapView.setTextureSize(this.mw.textureSize); + this.mapView.setTextureSize(Config.textureSize); GL11.glPushMatrix(); GL11.glLoadIdentity(); diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java index c2c335aa..14c7bbf3 100644 --- a/src/main/java/mapwriter/map/MapView.java +++ b/src/main/java/mapwriter/map/MapView.java @@ -5,6 +5,7 @@ import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Config; public class MapView { @@ -36,9 +37,9 @@ public class MapView { private boolean undergroundMode; public MapView(Mw mw) { - this.minZoom = mw.minZoom; - this.maxZoom = mw.maxZoom; - this.undergroundMode = mw.undergroundMode; + this.minZoom = Config.minZoom; + this.maxZoom = Config.maxZoom; + this.undergroundMode = Config.undergroundMode; this.setZoomLevel(0); this.setViewCentre(mw.playerX, mw.playerZ); } diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index 83e49d59..ea94b670 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -4,8 +4,8 @@ import java.util.List; import mapwriter.MwUtil; -import mapwriter.forge.MwConfig; import mapwriter.map.mapmode.MapMode; +import net.minecraftforge.common.config.Configuration; public class MarkerManager { @@ -21,7 +21,7 @@ public class MarkerManager { public MarkerManager() { } - public void load(MwConfig config, String category) { + public void load(Configuration config, String category) { this.markerList.clear(); if (config.hasCategory(category)) { @@ -45,7 +45,7 @@ public void load(MwConfig config, String category) { this.update(); } - public void save(MwConfig config, String category) { + public void save(Configuration config, String category) { config.get(category, "markerCount", 0).set(this.markerList.size()); config.get(category, "visibleGroup", "").set(this.visibleGroupName); diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index feacec3e..37e669ae 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -7,6 +7,8 @@ import mapwriter.map.mapmode.LargeMapMode; import mapwriter.map.mapmode.MapMode; import mapwriter.map.mapmode.SmallMapMode; +import mapwriter.util.Config; +import mapwriter.util.Reference; public class MiniMap { private Mw mw; @@ -27,25 +29,19 @@ public class MiniMap { private List mapList; private MapRenderer currentMap = null; - public int modeIndex = 0; - public MiniMap(Mw mw) { this.mw = mw; - // load config file options - this.modeIndex = mw.config.getOrSetInt(Mw.catOptions, "overlayModeIndex", this.modeIndex, 0, 1000); - int zoomLevel = mw.config.getOrSetInt(Mw.catOptions, "overlayZoomLevel", 0, mw.minZoom, mw.maxZoom); - // map view shared between large and small map modes this.view = new MapView(mw); - this.view.setZoomLevel(zoomLevel); + this.view.setZoomLevel(Config.zoomLevel); // small map mode - this.smallMapMode = new SmallMapMode(this.mw.config); + this.smallMapMode = new SmallMapMode(); this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); // large map mode - this.largeMapMode = new LargeMapMode(this.mw.config); + this.largeMapMode = new LargeMapMode(); this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); this.mapList = new ArrayList(); @@ -63,7 +59,7 @@ public MiniMap(Mw mw) { // sanitize overlayModeIndex loaded from config this.nextOverlayMode(0); - this.currentMap = this.mapList.get(this.modeIndex); + this.currentMap = this.mapList.get(Config.modeIndex); } public void close() { @@ -72,16 +68,13 @@ public void close() { this.smallMapMode.close(); this.largeMapMode.close(); - - this.mw.config.setInt(Mw.catOptions, "overlayModeIndex", this.modeIndex); - this.mw.config.setInt(Mw.catOptions, "overlayZoomLevel", this.view.getZoomLevel()); } // toggle between small map, underground map and no map public MapRenderer nextOverlayMode(int increment) { int size = this.mapList.size(); - this.modeIndex = (this.modeIndex + size + increment) % size; - this.currentMap = this.mapList.get(this.modeIndex); + Config.modeIndex = (Config.modeIndex + size + increment) % size; + this.currentMap = this.mapList.get(Config.modeIndex); return this.currentMap; } diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java index 641d3a41..fb926e27 100644 --- a/src/main/java/mapwriter/map/Trail.java +++ b/src/main/java/mapwriter/map/Trail.java @@ -5,7 +5,9 @@ import mapwriter.Mw; import mapwriter.Render; +import mapwriter.handler.ConfigurationHandler; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Reference; public class Trail { @@ -53,15 +55,15 @@ public void draw(MapMode mapMode, MapView mapView) { public Trail(Mw mw, String name) { this.mw = mw; this.name = name; - this.enabled = this.mw.config.getOrSetBoolean(Mw.catOptions, this.name + "TrailEnabled", false); - this.maxLength = this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength, 1, 200); - this.intervalMillis = (long) this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis, 100, 360000); + this.enabled = ConfigurationHandler.configuration.getBoolean(this.name + "TrailEnabled", Reference.catOptions, false, ""); + this.maxLength = ConfigurationHandler.configuration.getInt(this.name + "TrailMaxLength", Reference.catOptions, this.maxLength, 1, 200, ""); + this.intervalMillis = (long) ConfigurationHandler.configuration.getInt(this.name + "TrailMarkerIntervalMillis", Reference.catOptions, (int) this.intervalMillis, 100, 360000, ""); } public void close() { - this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); - this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); - this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); + //this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); + //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); + //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); this.trailMarkerList.clear(); } diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java index 6a990555..6e717f41 100644 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -1,10 +1,9 @@ package mapwriter.map.mapmode; -import mapwriter.forge.MwConfig; public class FullScreenMapMode extends MapMode { - public FullScreenMapMode(MwConfig config) { - super(config, "fullScreenMap"); + public FullScreenMapMode() { + super("fullScreenMap"); this.heightPercent = -1; this.marginTop = 0; diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java index 191ee8b4..15a12ccf 100644 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -1,10 +1,9 @@ package mapwriter.map.mapmode; -import mapwriter.forge.MwConfig; public class LargeMapMode extends MapMode { - public LargeMapMode(MwConfig config) { - super(config, "largeMap"); + public LargeMapMode() { + super("largeMap"); this.heightPercent = -1; this.marginTop = 10; diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index eec53bb9..52ccb94f 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -2,13 +2,12 @@ import java.awt.Point; -import mapwriter.forge.MwConfig; +import mapwriter.handler.ConfigurationHandler; import mapwriter.map.MapView; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; public class MapMode { - private final MwConfig config; public final String configCategory; private int sw = 320; @@ -46,41 +45,40 @@ public class MapMode { public int textY = 0; public int textColour = 0xffffffff; - public MapMode(MwConfig config, String configCategory) { - this.config = config; + public MapMode(String configCategory) { this.configCategory = configCategory; } public void loadConfig() { // get options from config file - this.enabled = this.config.getOrSetBoolean(this.configCategory, "enabled", this.enabled); - this.playerArrowSize = this.config.getOrSetInt(this.configCategory, "playerArrowSize", this.playerArrowSize, 1, 20); - this.markerSize = this.config.getOrSetInt(this.configCategory, "markerSize", this.markerSize, 1, 20); - this.alphaPercent = this.config.getOrSetInt(this.configCategory, "alphaPercent", this.alphaPercent, 0, 100); + this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, ""); + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, ""); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, ""); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, ""); - this.heightPercent = this.config.getOrSetInt(this.configCategory, "heightPercent", this.heightPercent, 0, 100); - this.marginTop = this.config.getOrSetInt(this.configCategory, "marginTop", this.marginTop, -1, 320); - this.marginBottom = this.config.getOrSetInt(this.configCategory, "marginBottom", this.marginBottom, -1, 320); - this.marginLeft = this.config.getOrSetInt(this.configCategory, "marginLeft", this.marginLeft, -1, 320); - this.marginRight = this.config.getOrSetInt(this.configCategory, "marginRight", this.marginRight, -1, 320); + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, ""); + this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, ""); + this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, ""); + this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, ""); + this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, ""); - this.rotate = this.config.getOrSetBoolean(this.configCategory, "rotate", this.rotate); - this.circular = this.config.getOrSetBoolean(this.configCategory, "circular", this.circular); - this.coordsEnabled = this.config.getOrSetBoolean(this.configCategory, "coordsEnabled", this.coordsEnabled); - this.borderMode = this.config.getOrSetInt(this.configCategory, "borderMode", this.borderMode, 0, 1); + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, ""); + this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, ""); + this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, ""); + this.borderMode = ConfigurationHandler.configuration.getInt("borderMode", this.configCategory, this.borderMode, 0, 1, ""); this.trailMarkerSize = Math.max(1, this.markerSize - 1); } public void saveConfig() { - this.config.setBoolean(this.configCategory, "enabled", this.enabled); - this.config.setInt(this.configCategory, "heightPercent", this.heightPercent); - this.config.setInt(this.configCategory, "marginTop", this.marginTop); - this.config.setInt(this.configCategory, "marginBottom", this.marginBottom); - this.config.setInt(this.configCategory, "marginLeft", this.marginLeft); - this.config.setInt(this.configCategory, "marginRight", this.marginRight); - this.config.setBoolean(this.configCategory, "rotate", this.rotate); - this.config.setBoolean(this.configCategory, "circular", this.circular); + //this.config.setBoolean(this.configCategory, "enabled", this.enabled); + //this.config.setInt(this.configCategory, "heightPercent", this.heightPercent); + //this.config.setInt(this.configCategory, "marginTop", this.marginTop); + //this.config.setInt(this.configCategory, "marginBottom", this.marginBottom); + //this.config.setInt(this.configCategory, "marginLeft", this.marginLeft); + //this.config.setInt(this.configCategory, "marginRight", this.marginRight); + //this.config.setBoolean(this.configCategory, "rotate", this.rotate); + //this.config.setBoolean(this.configCategory, "circular", this.circular); } public void close() { diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java index 20f4fd83..7daa1f9a 100644 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -1,10 +1,9 @@ package mapwriter.map.mapmode; -import mapwriter.forge.MwConfig; public class SmallMapMode extends MapMode { - public SmallMapMode(MwConfig config) { - super(config, "smallMap"); + public SmallMapMode() { + super("smallMap"); this.heightPercent = 30; this.marginTop = 10; diff --git a/src/main/java/mapwriter/util/Config.java b/src/main/java/mapwriter/util/Config.java new file mode 100644 index 00000000..e55674ab --- /dev/null +++ b/src/main/java/mapwriter/util/Config.java @@ -0,0 +1,30 @@ +package mapwriter.util; + +public class Config { + // configuration options + public static boolean linearTextureScalingEnabled = true; + public static int coordsMode = 0; + public static boolean undergroundMode = false; + public static boolean teleportEnabled = true; + public static String teleportCommand = "tp"; + public static int defaultTeleportHeight = 80; + public static int maxZoom = 5; + public static int minZoom = -5; + public static boolean useSavedBlockColours = false; + public static int maxChunkSaveDistSq = 128 * 128; + public static boolean mapPixelSnapEnabled = true; + public static int textureSize = 2048; + public static int configTextureSize = 2048; + public static int maxDeathMarkers = 3; + public static int chunksPerTick = 5; + public static boolean portNumberInWorldNameEnabled = true; + public static String saveDirOverride = ""; + public static boolean regionFileOutputEnabledSP = true; + public static boolean regionFileOutputEnabledMP = true; + public static int backgroundTextureMode = 0; + //public static boolean lightingEnabled = false; + + //World configuration Options + public static int modeIndex = 0; + public static int zoomLevel = 0; +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java new file mode 100644 index 00000000..38975752 --- /dev/null +++ b/src/main/java/mapwriter/util/Reference.java @@ -0,0 +1,15 @@ +package mapwriter.util; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public final static String catOptions = "options"; + + public final static String PlayerTrailName = "player"; +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java new file mode 100644 index 00000000..53ebcc9f --- /dev/null +++ b/src/main/java/mapwriter/util/Utils.java @@ -0,0 +1,19 @@ +package mapwriter.util; + +import java.util.List; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array to pass as default value + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + + return array; + } +} From df406f14b0d930f3b51cce527ee8416358c9e844 Mon Sep 17 00:00:00 2001 From: blt Date: Fri, 27 Mar 2015 12:04:12 +0100 Subject: [PATCH 023/109] Added Not Enough Keys Api --- .../modwarriors/notenoughkeys/api/Api.java | 41 ++++++++++++++++++ .../api/KeyBindingPressedEvent.java | 43 +++++++++++++++++++ .../notenoughkeys/api/package-info.java | 5 +++ 3 files changed, 89 insertions(+) create mode 100644 src/api/java/modwarriors/notenoughkeys/api/Api.java create mode 100644 src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java create mode 100644 src/api/java/modwarriors/notenoughkeys/api/package-info.java diff --git a/src/api/java/modwarriors/notenoughkeys/api/Api.java b/src/api/java/modwarriors/notenoughkeys/api/Api.java new file mode 100644 index 00000000..11bcf2c0 --- /dev/null +++ b/src/api/java/modwarriors/notenoughkeys/api/Api.java @@ -0,0 +1,41 @@ +package modwarriors.notenoughkeys.api; + +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Center of the API. Main api methods can be found in this class. + * + * @author TheTemportalist + */ +@SideOnly(Side.CLIENT) +public class Api { + + /** + * Checks if NotEnoughKeys is loaded in the current environment + * + * @return 'true' if loaded + */ + public static boolean isLoaded() { + return Loader.isModLoaded("notenoughkeys"); + } + + /** + * Registers a mod's keys with NEK + * + * @param modname The NAME of the mod registering the key + * @param keyDescriptions A String[] (Array[String]) of the key descriptions + * as an inherit array. i.e. ("modName", "key.hotbar1", "key.hotbar2") + */ + public static void registerMod(String modname, String... keyDescriptions) { + try { + Class.forName("modwarriors.notenoughkeys.keys.KeyHelper").getMethod( + "registerMod", String.class, String[].class + ).invoke(null, modname, keyDescriptions); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java b/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java new file mode 100644 index 00000000..4bce1eb7 --- /dev/null +++ b/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java @@ -0,0 +1,43 @@ +package modwarriors.notenoughkeys.api; + +import net.minecraftforge.fml.common.eventhandler.Cancelable; +import net.minecraftforge.fml.common.eventhandler.Event; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraft.client.settings.KeyBinding; + +/** + * Called when a keybinding is triggered with the passed with valid modifiers + * + * @author TheTemportalist + */ +@SideOnly(Side.CLIENT) +@Cancelable +public class KeyBindingPressedEvent extends Event { + + /** + * The KeyBinding being triggered + */ + public KeyBinding keyBinding = null; + /** + * Tells whether a modifier was required AND was down when triggered + */ + public boolean shiftRequired = false, ctrlRequired = false, altRequired = false; + + /** + * Called with the passed keyBinding and modifiers. + * Subscribe to this event so activate a keybinding when triggered. + * + * @param keyBinding The KeyBinding being triggered. Stores the key's description and keycode + * @param modifiers The modifiers (SHIFT, CTRL, ALT) that determine when a compatible key is pressed + */ + public KeyBindingPressedEvent(KeyBinding keyBinding, boolean[] modifiers) { + super(); + this.keyBinding = keyBinding; + this.shiftRequired = modifiers[0]; + this.ctrlRequired = modifiers[1]; + this.altRequired = modifiers[2]; + + } + +} diff --git a/src/api/java/modwarriors/notenoughkeys/api/package-info.java b/src/api/java/modwarriors/notenoughkeys/api/package-info.java new file mode 100644 index 00000000..4408965e --- /dev/null +++ b/src/api/java/modwarriors/notenoughkeys/api/package-info.java @@ -0,0 +1,5 @@ + +@API(owner = "Not Enough Keys", provides = "API_NEK", + apiVersion = "1.0.0") package modwarriors.notenoughkeys.api; + +import net.minecraftforge.fml.common.API; From 305a241b01990d31c0a6ce3f57e380f996fac184 Mon Sep 17 00:00:00 2001 From: blt Date: Fri, 27 Mar 2015 15:13:41 +0100 Subject: [PATCH 024/109] added not enough keys support --- .../java/mapwriter/forge/ClientProxy.java | 1 + .../java/mapwriter/forge/MwKeyHandler.java | 115 ++++++++++-------- src/main/java/mapwriter/util/Utils.java | 14 ++- 3 files changed, 80 insertions(+), 50 deletions(-) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 09316880..e0d8c63c 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -22,6 +22,7 @@ public void load() { Mw mw = new Mw(); MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); FMLCommonHandler.instance().bus().register(new MwKeyHandler()); + MinecraftForge.EVENT_BUS.register(new MwKeyHandler()); } public void postInit() { diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index bd6be920..fad2f9c6 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -1,16 +1,22 @@ package mapwriter.forge; +import java.util.ArrayList; + import mapwriter.Mw; +import mapwriter.util.Reference; +import modwarriors.notenoughkeys.api.Api; +import modwarriors.notenoughkeys.api.KeyBindingPressedEvent; import net.minecraft.client.settings.KeyBinding; - -import org.lwjgl.input.Keyboard; - import net.minecraftforge.fml.client.registry.ClientRegistry; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.Optional; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; -public class MwKeyHandler { +import org.lwjgl.input.Keyboard; +public class MwKeyHandler { + public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); public static KeyBinding keyNewMarker = new KeyBinding("key.mw_new_marker", Keyboard.KEY_INSERT, "Mapwriter"); public static KeyBinding keyMapMode = new KeyBinding("key.mw_next_map_mode", Keyboard.KEY_N, "Mapwriter"); @@ -21,50 +27,61 @@ public class MwKeyHandler { public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); //public static KeyBinding keyQuickLargeMap = new KeyBinding("key.mw_quick_large_map", Keyboard.KEY_NONE); - public MwKeyHandler(){ - ClientRegistry.registerKeyBinding(keyMapGui); - ClientRegistry.registerKeyBinding(keyNewMarker); - ClientRegistry.registerKeyBinding(keyMapMode); - ClientRegistry.registerKeyBinding(keyNextGroup); - ClientRegistry.registerKeyBinding(keyTeleport); - ClientRegistry.registerKeyBinding(keyZoomIn); - ClientRegistry.registerKeyBinding(keyZoomOut); - ClientRegistry.registerKeyBinding(keyUndergroundMode); + public final KeyBinding[] keys = + { + keyMapGui, + keyNewMarker, + keyMapMode, + keyNextGroup, + keyTeleport, + keyZoomIn, + keyZoomOut, + keyUndergroundMode + }; + + public MwKeyHandler() + { + ArrayList listKeyDescs = new ArrayList(); + // Register bindings + for (KeyBinding key : this.keys) + { + if (key != null) + { + ClientRegistry.registerKeyBinding(key); + } + listKeyDescs.add(key.getKeyDescription()); + } + + if (Loader.isModLoaded("notenoughkeys")) + { + Api.registerMod(Reference.MOD_ID, listKeyDescs.toArray(new String[0])); + } + } + + @SubscribeEvent + public void keyEvent(InputEvent.KeyInputEvent event) + { + if (!Loader.isModLoaded("notenoughkeys")) + { + this.checkKeys(); + } + } + + @Optional.Method(modid = "notenoughkeys") + @SubscribeEvent + public void keyEventSpecial(KeyBindingPressedEvent event) + { + Mw.instance.onKeyDown(event.keyBinding); + } + + private void checkKeys() + { + for (KeyBinding key : keys) + { + if (key != null && key.isPressed()) + { + Mw.instance.onKeyDown(key); + } + } } - - @SubscribeEvent - public void onKeyPress(InputEvent.KeyInputEvent event){ - if(keyMapGui.isPressed()){ - KeyBinding.setKeyBindState(keyMapGui.getKeyCode(), false); - Mw.instance.onKeyDown(keyMapGui); - } - if(keyNewMarker.isPressed()){ - KeyBinding.setKeyBindState(keyNewMarker.getKeyCode(), false); - Mw.instance.onKeyDown(keyNewMarker); - } - if(keyMapMode.isPressed()){ - KeyBinding.setKeyBindState(keyMapMode.getKeyCode(), false); - Mw.instance.onKeyDown(keyMapMode); - } - if(keyNextGroup.isPressed()){ - KeyBinding.setKeyBindState(keyNextGroup.getKeyCode(), false); - Mw.instance.onKeyDown(keyNextGroup); - } - if(keyTeleport.isPressed()){ - KeyBinding.setKeyBindState(keyTeleport.getKeyCode(), false); - Mw.instance.onKeyDown(keyTeleport); - } - if(keyZoomIn.isPressed()){ - KeyBinding.setKeyBindState(keyZoomIn.getKeyCode(), false); - Mw.instance.onKeyDown(keyZoomIn); - } - if(keyZoomOut.isPressed()){ - KeyBinding.setKeyBindState(keyZoomOut.getKeyCode(), false); - Mw.instance.onKeyDown(keyZoomOut); - } - if(keyUndergroundMode.isPressed()){ - KeyBinding.setKeyBindState(keyUndergroundMode.getKeyCode(), false); - Mw.instance.onKeyDown(keyUndergroundMode); - } - } } diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 53ebcc9f..5a832d94 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -6,7 +6,7 @@ public class Utils { public static int[] integerListToIntArray(List list) { - // convert List of integers to integer array to pass as default value + // convert List of integers to integer array int size = list.size(); int[] array = new int[size]; for (int i = 0; i < size; i++) @@ -16,4 +16,16 @@ public static int[] integerListToIntArray(List list) return array; } + + public static String[] StringListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + String[] array = new String[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } } From 13c5b99798516397d117e90927424dab179999c9 Mon Sep 17 00:00:00 2001 From: BlT Date: Fri, 27 Mar 2015 20:33:26 +0100 Subject: [PATCH 025/109] created the keyhandler twice. --- src/main/java/mapwriter/forge/ClientProxy.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index e0d8c63c..75480f65 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -21,8 +21,10 @@ public void preInit(File configFile) public void load() { Mw mw = new Mw(); MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); - FMLCommonHandler.instance().bus().register(new MwKeyHandler()); - MinecraftForge.EVENT_BUS.register(new MwKeyHandler()); + + Object eventhandler = new MwKeyHandler(); + FMLCommonHandler.instance().bus().register(eventhandler); + MinecraftForge.EVENT_BUS.register(eventhandler); } public void postInit() { From 11b56480047316c283cbcf668603a65661e54adf Mon Sep 17 00:00:00 2001 From: blt Date: Mon, 30 Mar 2015 09:29:55 +0200 Subject: [PATCH 026/109] Refractored Utils methods to different package --- .../java/mapwriter/BackgroundExecutor.java | 7 +- src/main/java/mapwriter/BlockColourGen.java | 7 +- src/main/java/mapwriter/ChunkManager.java | 3 +- src/main/java/mapwriter/Mw.java | 49 +++--- src/main/java/mapwriter/MwUtil.java | 121 --------------- src/main/java/mapwriter/Render.java | 5 +- src/main/java/mapwriter/Texture.java | 15 +- src/main/java/mapwriter/gui/MwGui.java | 32 ++-- .../java/mapwriter/map/MarkerManager.java | 9 +- src/main/java/mapwriter/tasks/MergeTask.java | 4 +- .../mapwriter/tasks/RebuildRegionsTask.java | 4 +- src/main/java/mapwriter/util/Logging.java | 28 ++++ src/main/java/mapwriter/util/Reference.java | 34 +++-- src/main/java/mapwriter/util/Utils.java | 141 ++++++++++++++---- 14 files changed, 233 insertions(+), 226 deletions(-) delete mode 100644 src/main/java/mapwriter/MwUtil.java create mode 100644 src/main/java/mapwriter/util/Logging.java diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index 4c8caf13..caa5fc26 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -7,6 +7,7 @@ import java.util.concurrent.TimeUnit; import mapwriter.tasks.Task; +import mapwriter.util.Logging; @@ -65,7 +66,7 @@ public boolean addTask(Task task) { task.setFuture(future); this.taskQueue.add(task); } else { - MwUtil.log("MwExecutor.addTask: error: cannot add task to closed executor"); + Logging.log("MwExecutor.addTask: error: cannot add task to closed executor"); } return this.closed; } @@ -76,7 +77,7 @@ public boolean addTask2(Task task) { task.setFuture(future); this.taskQueue.add(task); } else { - MwUtil.log("MwExecutor.addTask: error: cannot add task to closed executor"); + Logging.log("MwExecutor.addTask: error: cannot add task to closed executor"); } return this.closed; } @@ -128,7 +129,7 @@ public boolean close() { error = !this.executor.awaitTermination(10L, TimeUnit.SECONDS); error = false; } catch (InterruptedException e) { - MwUtil.log("error: IO task was interrupted during shutdown"); + Logging.log("error: IO task was interrupted during shutdown"); e.printStackTrace(); } this.closed = true; diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 8e621fac..6c3b6a22 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -2,6 +2,7 @@ import mapwriter.region.BlockColours; import mapwriter.region.BlockColours.BlockType; +import mapwriter.util.Logging; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -88,7 +89,7 @@ private static void genBiomeColours(BlockColours bc) { public static void genBlockColours(BlockColours bc) { - MwUtil.log("generating block map colours from textures"); + Logging.log("generating block map colours from textures"); // copy terrain texture to MwRender pixel bytebuffer @@ -101,7 +102,7 @@ public static void genBlockColours(BlockColours bc) { // create texture object from the currently bound GL texture if (terrainTextureId == 0) { - MwUtil.log("error: could get terrain texture ID"); + Logging.log("error: could get terrain texture ID"); return; } Texture terrainTexture = new Texture(terrainTextureId); @@ -182,7 +183,7 @@ public static void genBlockColours(BlockColours bc) { } } - MwUtil.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); + Logging.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); genBiomeColours(bc); } diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index b357ae06..d369f192 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -8,6 +8,7 @@ import mapwriter.tasks.SaveChunkTask; import mapwriter.tasks.UpdateSurfaceChunksTask; import mapwriter.util.Config; +import mapwriter.util.Utils; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; @@ -107,7 +108,7 @@ public void updateSurfaceChunks() { Chunk chunk = entry.getKey(); int flags = entry.getValue(); - if (MwUtil.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { + if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { flags |= (VISIBLE_FLAG | VIEWED_FLAG); } else { flags &= ~VISIBLE_FLAG; diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index e93a063e..a8164669 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -21,6 +21,7 @@ import mapwriter.region.RegionManager; import mapwriter.tasks.CloseRegionManagerTask; import mapwriter.util.Config; +import mapwriter.util.Logging; import mapwriter.util.Reference; import mapwriter.util.Utils; import net.minecraft.client.Minecraft; @@ -123,7 +124,7 @@ public String getWorldName() { // strip invalid characters from the server name so that it // can't be something malicious like '..\..\..\windows\' - worldName = MwUtil.mungeString(worldName); + worldName = Utils.mungeString(worldName); // if something went wrong make sure the name is not blank // (causes crash on start up due to empty configuration section) @@ -159,9 +160,9 @@ public void setTextureSize() { } textureSize /= 2; - MwUtil.log("GL reported max texture size = %d", maxTextureSize); - MwUtil.log("texture size from config = %d", Config.configTextureSize); - MwUtil.log("setting map texture size to = %d", textureSize); + Logging.log("GL reported max texture size = %d", maxTextureSize); + Logging.log("texture size from config = %d", Config.configTextureSize); + Logging.log("setting map texture size to = %d", textureSize); Config.textureSize = textureSize; if (this.ready) { @@ -223,7 +224,7 @@ public void teleportTo(int x, int y, int z) { if (Config.teleportEnabled) { this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); } else { - MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); } } @@ -232,7 +233,7 @@ public void warpTo(String name) { //MwUtil.printBoth(String.format("warping to %s", name)); this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); } else { - MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); } } @@ -241,7 +242,7 @@ public void teleportToMapPos(MapView mapView, int x, int y, int z) { double scale = mapView.getDimensionScaling(this.playerDimension); this.teleportTo((int) (x / scale), y, (int) (z / scale)); } else { - MwUtil.printBoth("teleport command is set to 'warp', can only warp to markers"); + Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); } } @@ -251,29 +252,29 @@ public void teleportToMarker(Marker marker) { } else if (marker.dimension == this.playerDimension) { this.teleportTo(marker.x, marker.y, marker.z); } else { - MwUtil.printBoth("cannot teleport to marker in different dimension"); + Utils.printBoth("cannot teleport to marker in different dimension"); } } public void loadBlockColourOverrides(BlockColours bc) { File f = new File(this.configDir, blockColourOverridesFileName); if (f.isFile()) { - MwUtil.logInfo("loading block colour overrides file %s", f); + Logging.logInfo("loading block colour overrides file %s", f); bc.loadFromFile(f); } else { - MwUtil.logInfo("recreating block colour overrides file %s", f); + Logging.logInfo("recreating block colour overrides file %s", f); BlockColours.writeOverridesFile(f); if (f.isFile()) { bc.loadFromFile(f); } else { - MwUtil.logError("could not load block colour overrides from file %s", f); + Logging.logError("could not load block colour overrides from file %s", f); } } } public void saveBlockColours(BlockColours bc) { File f = new File(this.configDir, blockColourSaveFileName); - MwUtil.logInfo("saving block colours to '%s'", f); + Logging.logInfo("saving block colours to '%s'", f); bc.saveToFile(f); } @@ -282,12 +283,12 @@ public void reloadBlockColours() { File f = new File(this.configDir, blockColourSaveFileName); if (Config.useSavedBlockColours && f.isFile()) { // load block colours from file - MwUtil.logInfo("loading block colours from %s", f); + Logging.logInfo("loading block colours from %s", f); bc.loadFromFile(f); this.loadBlockColourOverrides(bc); } else { // generate block colours from current texture pack - MwUtil.logInfo("generating block colours"); + Logging.logInfo("generating block colours"); // block type overrides need to be loaded before the block colours are generated this.loadBlockColourOverrides(bc); BlockColourGen.genBlockColours(bc); @@ -348,11 +349,11 @@ public void load() { } if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { - MwUtil.log("Mw.load: world or player is null, cannot load yet"); + Logging.log("Mw.load: world or player is null, cannot load yet"); return; } - MwUtil.log("Mw.load: loading..."); + Logging.log("Mw.load: loading..."); IntegratedServer server = this.mc.getIntegratedServer(); this.multiplayer = (server == null); @@ -366,7 +367,7 @@ public void load() { if (d.isDirectory()) { saveDir = d; } else { - MwUtil.log("error: no such directory %s", Config.saveDirOverride); + Logging.log("error: no such directory %s", Config.saveDirOverride); } } @@ -384,7 +385,7 @@ public void load() { this.imageDir.mkdirs(); } if (!this.imageDir.isDirectory()) { - MwUtil.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); + Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); } this.tickCounter = 0; @@ -422,7 +423,7 @@ public void load() { public void close() { - MwUtil.log("Mw.close: closing..."); + Logging.log("Mw.close: closing..."); if (this.ready) { this.ready = false; @@ -435,11 +436,11 @@ public void close() { this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); this.regionManager = null; - MwUtil.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); + Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); if (this.executor.close()) { - MwUtil.log("error: timeout waiting for tasks to finish"); + Logging.log("error: timeout waiting for tasks to finish"); } - MwUtil.log("done"); + Logging.log("done"); this.playerTrail.close(); @@ -512,7 +513,7 @@ public void onChunkLoad(Chunk chunk) { if (this.ready) { this.chunkManager.addChunk(chunk); } else { - MwUtil.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); + Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); } } } @@ -538,7 +539,7 @@ public void onPlayerDeath(EntityPlayerMP player) { this.markerManager.delMarker(null, "playerDeaths"); } - this.markerManager.addMarker(MwUtil.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); + this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); this.markerManager.setVisibleGroupName("playerDeaths"); this.markerManager.update(); } diff --git a/src/main/java/mapwriter/MwUtil.java b/src/main/java/mapwriter/MwUtil.java deleted file mode 100644 index ee93847b..00000000 --- a/src/main/java/mapwriter/MwUtil.java +++ /dev/null @@ -1,121 +0,0 @@ -package mapwriter; - -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.regex.Pattern; - -import mapwriter.forge.MwForge; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class MwUtil { - - public final static Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - - public static void logInfo(String s, Object...args) { - MwForge.logger.info(String.format(s, args)); - } - - public static void logWarning(String s, Object...args) { - MwForge.logger.warn(String.format(s, args)); - } - - public static void logError(String s, Object...args) { - MwForge.logger.error(String.format(s, args)); - } - - public static void debug(String s, Object...args) { - MwForge.logger.debug(String.format(s, args)); - } - - public static void log(String s, Object...args) { - logInfo(String.format(s, args)); - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - MwUtil.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } -} diff --git a/src/main/java/mapwriter/Render.java b/src/main/java/mapwriter/Render.java index 1070392b..b2ace36a 100644 --- a/src/main/java/mapwriter/Render.java +++ b/src/main/java/mapwriter/Render.java @@ -1,5 +1,6 @@ package mapwriter; +import mapwriter.util.Logging; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; @@ -131,7 +132,7 @@ public static void printBoundTextureInfo(int texture) { int h = getTextureHeight(); int depth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL12.GL_TEXTURE_DEPTH); int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); - MwUtil.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); + Logging.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); } public static int getMaxTextureSize() { @@ -169,7 +170,7 @@ public static void drawTexturedRect(double x, double y, double w, double h, doub tessellator.draw(); GL11.glDisable(GL11.GL_BLEND); } catch (NullPointerException e) { - MwUtil.log("MwRender.drawTexturedRect: null pointer exception"); + Logging.log("MwRender.drawTexturedRect: null pointer exception"); } } diff --git a/src/main/java/mapwriter/Texture.java b/src/main/java/mapwriter/Texture.java index b4944b40..082a01ed 100644 --- a/src/main/java/mapwriter/Texture.java +++ b/src/main/java/mapwriter/Texture.java @@ -2,6 +2,9 @@ import java.nio.IntBuffer; +import mapwriter.util.Logging; +import mapwriter.util.Utils; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -17,7 +20,7 @@ public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int t this.id = GL11.glGenTextures(); this.w = w; this.h = h; - this.pixelBuf = MwUtil.allocateDirectIntBuffer(w * h); + this.pixelBuf = Utils.allocateDirectIntBuffer(w * h); this.fillRect(0, 0, w, h, fillColour); this.pixelBuf.position(0); this.bind(); @@ -35,9 +38,9 @@ public Texture(int id) { this.bind(); this.w = Render.getTextureWidth(); this.h = Render.getTextureHeight(); - this.pixelBuf = MwUtil.allocateDirectIntBuffer(this.w * this.h); + this.pixelBuf = Utils.allocateDirectIntBuffer(this.w * this.h); this.getPixelsFromExistingTexture(); - MwUtil.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); + Logging.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); } // free up the resources used by the GL texture @@ -46,7 +49,7 @@ public synchronized void close() { try { GL11.glDeleteTextures(this.id); } catch (NullPointerException e) { - MwUtil.log("MwTexture.close: null pointer exception (texture %d)", this.id); + Logging.log("MwTexture.close: null pointer exception (texture %d)", this.id); } this.id = 0; } @@ -129,7 +132,7 @@ public synchronized void updateTextureArea(int x, int y, int w, int h) { GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); } catch (NullPointerException e) { - MwUtil.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); + Logging.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); } } @@ -149,7 +152,7 @@ private synchronized void getPixelsFromExistingTexture() { // this.pixelBuf.flip() this.pixelBuf.limit(this.w * this.h); } catch (NullPointerException e) { - MwUtil.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); + Logging.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); } } } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 8e533f03..65cb979d 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -4,7 +4,6 @@ import java.io.IOException; import mapwriter.Mw; -import mapwriter.MwUtil; import mapwriter.api.IMwDataProvider; import mapwriter.api.MwAPI; import mapwriter.forge.MwKeyHandler; @@ -16,6 +15,9 @@ import mapwriter.tasks.MergeTask; import mapwriter.tasks.RebuildRegionsTask; import mapwriter.util.Config; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.BlockPos; @@ -175,11 +177,11 @@ public void mergeMapViewToImage() { this.mw.worldDir, this.mw.worldDir.getName())); - MwUtil.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); + Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); } public void regenerateView() { - MwUtil.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", + Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), (int) this.mapView.getMinX(), @@ -323,13 +325,8 @@ public void handleMouseInput() throws IOException { } // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) { - //MwUtil.log("MwGui.mouseClicked(%d, %d, %d)", x, y, button); - - //int bX = this.mouseToBlockX(x); - //int bZ = this.mouseToBlockZ(y); - //int bY = this.getHeightAtBlockPos(bX, bZ); - + protected void mouseClicked(int x, int y, int button) + { Marker marker = this.getMarkerNearScreenPos(x, y); Marker prevMarker = this.mw.markerManager.selectedMarker; @@ -343,8 +340,19 @@ protected void mouseClicked(int x, int y, int button) { this.mapView.getDimension() ) ); - } else if (this.optionsLabel.posWithin(x, y)) { - this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else if (this.optionsLabel.posWithin(x, y)) + { + try + { + GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } + catch (Exception e) + { + Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); + } + + //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); } else { this.mouseLeftHeld = 1; this.mouseLeftDragStartX = x; diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index ea94b670..98f85223 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -3,8 +3,9 @@ import java.util.ArrayList; import java.util.List; -import mapwriter.MwUtil; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Logging; +import mapwriter.util.Utils; import net.minecraftforge.common.config.Configuration; public class MarkerManager { @@ -36,7 +37,7 @@ public void load(Configuration config, String category) { if (marker != null) { this.addMarker(marker); } else { - MwUtil.log("error: could not load " + key + " from config file"); + Logging.log("error: could not load " + key + " from config file"); } } } @@ -60,7 +61,7 @@ public void save(Configuration config, String category) { public void setVisibleGroupName(String groupName) { if (groupName != null) { - this.visibleGroupName = MwUtil.mungeString(groupName); + this.visibleGroupName = Utils.mungeString(groupName); } else { this.visibleGroupName = "none"; } @@ -109,7 +110,7 @@ public Marker stringToMarker(String s) { marker = null; } } else { - MwUtil.log("Marker.stringToMarker: invalid marker '%s'", s); + Logging.log("Marker.stringToMarker: invalid marker '%s'", s); } return marker; } diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java index 7f23cc38..ca435bd1 100644 --- a/src/main/java/mapwriter/tasks/MergeTask.java +++ b/src/main/java/mapwriter/tasks/MergeTask.java @@ -2,9 +2,9 @@ import java.io.File; -import mapwriter.MwUtil; import mapwriter.region.MergeToImage; import mapwriter.region.RegionManager; +import mapwriter.util.Utils; public class MergeTask extends Task { @@ -37,7 +37,7 @@ public void run() { @Override public void onComplete() { - MwUtil.printBoth(this.msg); + Utils.printBoth(this.msg); } } diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java index 9e8823f3..937d35fd 100644 --- a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java +++ b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java @@ -1,9 +1,9 @@ package mapwriter.tasks; import mapwriter.Mw; -import mapwriter.MwUtil; import mapwriter.region.BlockColours; import mapwriter.region.RegionManager; +import mapwriter.util.Utils; public class RebuildRegionsTask extends Task { @@ -30,7 +30,7 @@ public void run() { @Override public void onComplete() { - MwUtil.printBoth("rebuild task complete"); + Utils.printBoth("rebuild task complete"); } } diff --git a/src/main/java/mapwriter/util/Logging.java b/src/main/java/mapwriter/util/Logging.java new file mode 100644 index 00000000..4ce854b5 --- /dev/null +++ b/src/main/java/mapwriter/util/Logging.java @@ -0,0 +1,28 @@ +package mapwriter.util; + +import java.util.regex.Pattern; + +import mapwriter.forge.MwForge; + +public class Logging +{ + public static void logInfo(String s, Object...args) { + MwForge.logger.info(String.format(s, args)); + } + + public static void logWarning(String s, Object...args) { + MwForge.logger.warn(String.format(s, args)); + } + + public static void logError(String s, Object...args) { + MwForge.logger.error(String.format(s, args)); + } + + public static void debug(String s, Object...args) { + MwForge.logger.debug(String.format(s, args)); + } + + public static void log(String s, Object...args) { + logInfo(String.format(s, args)); + } +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 38975752..b7912020 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,15 +1,19 @@ -package mapwriter.util; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public final static String catOptions = "options"; - - public final static String PlayerTrailName = "player"; -} +package mapwriter.util; + +import java.util.regex.Pattern; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public final static String catOptions = "options"; + + public final static String PlayerTrailName = "player"; + + public final static Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 5a832d94..14162e7a 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,31 +1,110 @@ -package mapwriter.util; - -import java.util.List; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - - return array; - } - - public static String[] StringListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - String[] array = new String[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } -} +package mapwriter.util; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + public static void printBoth(String msg) { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } +} From 668906febbf2bb25ee157c08f5f18b761e95ebd4 Mon Sep 17 00:00:00 2001 From: blt Date: Mon, 30 Mar 2015 13:54:13 +0200 Subject: [PATCH 027/109] Updated buildscript to make it more generic for me --- build.gradle | 200 +++++++++++++++++++++++++++++---------------------- 1 file changed, 115 insertions(+), 85 deletions(-) diff --git a/build.gradle b/build.gradle index 33e14cec..a787cee0 100644 --- a/build.gradle +++ b/build.gradle @@ -1,86 +1,116 @@ -buildscript { - repositories { - mavenCentral() - maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" - } - maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" - } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' - } -} - -apply plugin: 'forge' - -repositories { - mavenLocal() -} - -// Define properties file -ext.configFile = file "build.properties" - -configFile.withReader { -// Load config. It shall from now be referenced as simply config or project.config -def prop = new Properties() -prop.load(it) -project.ext.config = new ConfigSlurper().parse prop -} - -dependencies { -} - -group= config.mod_group -version = config.mod_version -archivesBaseName = config.mod_name - - -minecraft { -version = config.mc_version + "-" + config.forge_version -runDir = "eclipse" -mappings = config.mcp_version -replace '@MOD_VERSION@', config.mod_version -} - -processResources -{ - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - - // replace version and mcversion - expand 'version':project.version, 'mcversion':project.minecraft.version - } - - // copy everything else, thats not the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - } -} - -jar { -classifier = 'universal' -} - -task sourceJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'src' -} - -task devJar(type: Jar) { -from sourceSets.main.output -classifier = 'dev' -} - -artifacts { - archives sourceJar - archives devJar +buildscript { + repositories { + mavenCentral() + maven { + name = "forge" + url = "http://files.minecraftforge.net/maven" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/repositories/snapshots/" + } + } + dependencies { + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + } +} + +apply plugin: 'forge' + +repositories { + mavenLocal() +} + +// Define properties file +ext.configFile = file "build.properties" + +configFile.withReader { +// Load config. It shall from now be referenced as simply config or project.config +def prop = new Properties() +prop.load(it) +project.ext.config = new ConfigSlurper().parse prop +} + +dependencies { + if (config.isSet('dependicies')) { + def dep = config.dependicies.split(", ") + dep.each { compile it } + } +} + +group= config.mod_group +version = config.mod_version +archivesBaseName = config.mod_name + + +minecraft { +version = config.mc_version + "-" + config.forge_version +runDir = "eclipse" +mappings = config.mcp_version +replace '@MOD_VERSION@', config.mod_version +} + +processResources +{ + // this will ensure that this task is redone when the versions change. + inputs.property "version", project.version + inputs.property "mcversion", project.minecraft.version + + // replace stuff in mcmod.info, nothing else + from(sourceSets.main.resources.srcDirs) { + include 'mcmod.info' + + // replace version and mcversion + expand 'version':project.version, 'mcversion':project.minecraft.version + } + + // copy everything else, thats not the mcmod.info + from(sourceSets.main.resources.srcDirs) { + exclude 'mcmod.info' + } +} + +jar { +classifier = 'universal' +} + +task sourceJar(type: Jar) { + from sourceSets.main.allSource + classifier = 'src' +} + +task devJar(type: Jar) { +from sourceSets.main.output +classifier = 'dev' +} + +artifacts { + archives sourceJar + archives devJar +} + +eclipse { + // replace absolute paths with classpath variable GRADLE_CACHE + pathVariables 'GRADLE_CACHE': gradle.gradleUserHomeDir +} + +eclipse.classpath.file.whenMerged { classpath -> + classpath.entries.each { entry -> + if (entry.kind == 'lib') { + // for jar files referenced in project folder, use relative path + def prefix = projectDir.absolutePath.replace('\\', '/') + entry.path = entry.path.replace(prefix, "/$eclipse.project.name") + } + } +} + +gradle.taskGraph.whenReady { taskGraph -> + if (!taskGraph.allTasks.findAll{ it.name == 'eclipseClasspath' }.empty) { + gradle.buildFinished { + println '----------------------------------------------------------------------' + print "Please set the Eclipse classpath variable 'GRADLE_USER_HOME' in Preferences " + println "-> Java -> Build path -> Classpath Variable to $gradle.gradleUserHomeDir" + println '----------------------------------------------------------------------' + } + } } \ No newline at end of file From 186fcfd8eb843e2357c2c62192a6b99e7039b3bd Mon Sep 17 00:00:00 2001 From: blt Date: Mon, 30 Mar 2015 13:56:11 +0200 Subject: [PATCH 028/109] More Refractoring --- src/main/java/mapwriter/BlockColourGen.java | 2 ++ src/main/java/mapwriter/Mw.java | 1 + src/main/java/mapwriter/map/MapRenderer.java | 2 +- src/main/java/mapwriter/map/MapTexture.java | 2 +- src/main/java/mapwriter/map/Marker.java | 2 +- src/main/java/mapwriter/map/Trail.java | 2 +- src/main/java/mapwriter/map/UndergroundTexture.java | 2 +- src/main/java/mapwriter/{ => util}/Render.java | 3 +-- src/main/java/mapwriter/{ => util}/Texture.java | 5 +---- 9 files changed, 10 insertions(+), 11 deletions(-) rename src/main/java/mapwriter/{ => util}/Render.java (99%) rename src/main/java/mapwriter/{ => util}/Texture.java (98%) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 6c3b6a22..1bad0f0d 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -3,6 +3,8 @@ import mapwriter.region.BlockColours; import mapwriter.region.BlockColours.BlockType; import mapwriter.util.Logging; +import mapwriter.util.Render; +import mapwriter.util.Texture; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index a8164669..3a249817 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -23,6 +23,7 @@ import mapwriter.util.Config; import mapwriter.util.Logging; import mapwriter.util.Reference; +import mapwriter.util.Render; import mapwriter.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 583851f2..08fd3b83 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -4,12 +4,12 @@ import java.util.ArrayList; import mapwriter.Mw; -import mapwriter.Render; import mapwriter.api.IMwChunkOverlay; import mapwriter.api.IMwDataProvider; import mapwriter.api.MwAPI; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Config; +import mapwriter.util.Render; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/mapwriter/map/MapTexture.java b/src/main/java/mapwriter/map/MapTexture.java index 921f4e39..33b67ac8 100644 --- a/src/main/java/mapwriter/map/MapTexture.java +++ b/src/main/java/mapwriter/map/MapTexture.java @@ -4,9 +4,9 @@ import java.util.List; import mapwriter.BackgroundExecutor; -import mapwriter.Texture; import mapwriter.region.Region; import mapwriter.region.RegionManager; +import mapwriter.util.Texture; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index e1958655..3b78c42c 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -2,8 +2,8 @@ import java.awt.Point; -import mapwriter.Render; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Render; public class Marker { public final String name; diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java index fb926e27..41843da5 100644 --- a/src/main/java/mapwriter/map/Trail.java +++ b/src/main/java/mapwriter/map/Trail.java @@ -4,10 +4,10 @@ import java.util.LinkedList; import mapwriter.Mw; -import mapwriter.Render; import mapwriter.handler.ConfigurationHandler; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Reference; +import mapwriter.util.Render; public class Trail { diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java index 87a28bb4..23845680 100644 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -4,9 +4,9 @@ import java.util.Arrays; import mapwriter.Mw; -import mapwriter.Texture; import mapwriter.region.ChunkRender; import mapwriter.region.IChunk; +import mapwriter.util.Texture; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.util.BlockPos; diff --git a/src/main/java/mapwriter/Render.java b/src/main/java/mapwriter/util/Render.java similarity index 99% rename from src/main/java/mapwriter/Render.java rename to src/main/java/mapwriter/util/Render.java index b2ace36a..a54348ea 100644 --- a/src/main/java/mapwriter/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -1,6 +1,5 @@ -package mapwriter; +package mapwriter.util; -import mapwriter.util.Logging; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; diff --git a/src/main/java/mapwriter/Texture.java b/src/main/java/mapwriter/util/Texture.java similarity index 98% rename from src/main/java/mapwriter/Texture.java rename to src/main/java/mapwriter/util/Texture.java index 082a01ed..5139ef0f 100644 --- a/src/main/java/mapwriter/Texture.java +++ b/src/main/java/mapwriter/util/Texture.java @@ -1,10 +1,7 @@ -package mapwriter; +package mapwriter.util; import java.nio.IntBuffer; -import mapwriter.util.Logging; -import mapwriter.util.Utils; - import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; From 5456ff9a3c0870593e8f49c33fc2d4524a0af35e Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 7 Apr 2015 22:27:23 +0200 Subject: [PATCH 029/109] redid the config options to the new forge ingame config. --- src/main/java/mapwriter/Mw.java | 1204 ++++++++------- src/main/java/mapwriter/api/package-info.java | 6 + src/main/java/mapwriter/gui/ModGuiConfig.java | 139 +- src/main/java/mapwriter/gui/MwGui.java | 1291 +++++++++-------- .../java/mapwriter/gui/MwGuiOptionSlot.java | 232 --- src/main/java/mapwriter/gui/MwGuiOptions.java | 63 - .../handler/ConfigurationHandler.java | 73 +- src/main/java/mapwriter/map/MapRenderer.java | 640 ++++---- src/main/java/mapwriter/map/Marker.java | 4 +- src/main/java/mapwriter/map/MiniMap.java | 175 ++- src/main/java/mapwriter/map/Trail.java | 200 +-- .../map/mapmode/FullScreenMapMode.java | 36 +- .../mapwriter/map/mapmode/LargeMapMode.java | 32 +- .../java/mapwriter/map/mapmode/MapMode.java | 460 +++--- .../mapwriter/map/mapmode/SmallMapMode.java | 32 +- src/main/java/mapwriter/util/Config.java | 34 +- .../java/mapwriter/util/MapModeConfig.java | 64 + src/main/java/mapwriter/util/Reference.java | 41 +- 18 files changed, 2303 insertions(+), 2423 deletions(-) create mode 100644 src/main/java/mapwriter/api/package-info.java delete mode 100644 src/main/java/mapwriter/gui/MwGuiOptionSlot.java delete mode 100644 src/main/java/mapwriter/gui/MwGuiOptions.java create mode 100644 src/main/java/mapwriter/util/MapModeConfig.java diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 3a249817..bb255acd 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -1,607 +1,597 @@ -package mapwriter; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.forge.MwForge; -import mapwriter.forge.MwKeyHandler; -import mapwriter.gui.MwGui; -import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.MapTexture; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.map.MiniMap; -import mapwriter.map.Trail; -import mapwriter.map.UndergroundTexture; -import mapwriter.overlay.OverlaySlime; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; -import mapwriter.tasks.CloseRegionManagerTask; -import mapwriter.util.Config; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Render; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.config.Configuration; - -public class Mw { - - public Minecraft mc = null; - - // configuration files (global and world specific) - public static Configuration worldConfig = null; - - // server information - public String worldName = "default"; - private String serverName = "default"; - private int serverPort = 0; - - // directories - private final File configDir; - private final File saveDir; - public File worldDir = null; - public File imageDir = null; - - // flags and counters - public boolean ready = false; - public boolean multiplayer = false; - public int tickCounter = 0; - - // list of available dimensions - public List dimensionList = new ArrayList(); - - // player position and heading - public double playerX = 0.0; - public double playerZ = 0.0; - public double playerY = 0.0; - public int playerXInt = 0; - public int playerYInt = 0; - public int playerZInt = 0; - public double playerHeading = 0.0; - public int playerDimension = 0; - public double mapRotationDegrees = 0.0; - - // constants - public final static String catWorld = "world"; - public final static String catMarkers = "markers"; - public final static String worldDirConfigName = "mapwriter.cfg"; - public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - // instances of components - public MapTexture mapTexture = null; - public UndergroundTexture undergroundMapTexture = null; - public BackgroundExecutor executor = null; - public MiniMap miniMap = null; - public MarkerManager markerManager = null; - public BlockColours blockColours = null; - public RegionManager regionManager = null; - public ChunkManager chunkManager = null; - public Trail playerTrail = null; - - public static Mw instance; - - public Mw() { - // client only initialization - this.mc = Minecraft.getMinecraft(); - - // create base save directory - this.saveDir = new File(this.mc.mcDataDir, "saves"); - this.configDir = new File(this.mc.mcDataDir, "config"); - - this.ready = false; - - RegionManager.logger = MwForge.logger; - - instance = this; - - ConfigurationHandler.loadConfig(); - } - - public String getWorldName() { - String worldName; - if (this.multiplayer) { - if (Config.portNumberInWorldNameEnabled) { - worldName = String.format("%s_%d", this.serverName, this.serverPort); - } else { - worldName = String.format("%s", this.serverName); - } - - } else { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = this.mc.getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = Utils.mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - public void loadWorldConfig() { - // load world specific config file - File worldConfigFile = new File(this.worldDir, worldDirConfigName); - this.worldConfig = new Configuration(worldConfigFile); - this.worldConfig.load(); - - this.dimensionList.clear(); - this.worldConfig.get(catWorld, "dimensionList", Utils.integerListToIntArray(this.dimensionList)); - this.addDimension(0); - this.cleanDimensionList(); - } - - public void saveWorldConfig() { - //this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); - this.worldConfig.save(); - } - - public void setTextureSize() { - if (Config.configTextureSize != Config.textureSize) { - int maxTextureSize = Render.getMaxTextureSize(); - int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { - textureSize *= 2; - } - textureSize /= 2; - - Logging.log("GL reported max texture size = %d", maxTextureSize); - Logging.log("texture size from config = %d", Config.configTextureSize); - Logging.log("setting map texture size to = %d", textureSize); - - Config.textureSize = textureSize; - if (this.ready) { - // if we are already up and running need to close and reinitialize the map texture and - // region manager. - this.reloadMapTexture(); - } - } - } - - // update the saved player position and orientation - // called every tick - public void updatePlayer() { - // get player pos - this.playerX = (double) this.mc.thePlayer.posX; - this.playerY = (double) this.mc.thePlayer.posY; - this.playerZ = (double) this.mc.thePlayer.posZ; - this.playerXInt = (int) Math.floor(this.playerX); - this.playerYInt = (int) Math.floor(this.playerY); - this.playerZInt = (int) Math.floor(this.playerZ); - - // rotationYaw of 0 points due north, we want it to point due east instead - // so add pi/2 radians (90 degrees) - this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); - this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; - - // set by onWorldLoad - this.playerDimension = this.mc.theWorld.provider.getDimensionId(); - if (this.miniMap.view.getDimension() != this.playerDimension) - { - this.addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); - } - } - - public void addDimension(int dimension) { - int i = this.dimensionList.indexOf(dimension); - if (i < 0) { - this.dimensionList.add(dimension); - } - } - - public void cleanDimensionList() { - List dimensionListCopy = new ArrayList(this.dimensionList); - this.dimensionList.clear(); - for (int dimension : dimensionListCopy) { - this.addDimension(dimension); - } - } - - public void toggleMarkerMode() { - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - } - - // cheap and lazy way to teleport... - public void teleportTo(int x, int y, int z) { - if (Config.teleportEnabled) { - this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void warpTo(String name) { - if (Config.teleportEnabled) { - //MwUtil.printBoth(String.format("warping to %s", name)); - this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!Config.teleportCommand.equals("warp")) { - double scale = mapView.getDimensionScaling(this.playerDimension); - this.teleportTo((int) (x / scale), y, (int) (z / scale)); - } else { - Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); - } - } - - public void teleportToMarker(Marker marker) { - if (Config.teleportCommand.equals("warp")) { - this.warpTo(marker.name); - } else if (marker.dimension == this.playerDimension) { - this.teleportTo(marker.x, marker.y, marker.z); - } else { - Utils.printBoth("cannot teleport to marker in different dimension"); - } - } - - public void loadBlockColourOverrides(BlockColours bc) { - File f = new File(this.configDir, blockColourOverridesFileName); - if (f.isFile()) { - Logging.logInfo("loading block colour overrides file %s", f); - bc.loadFromFile(f); - } else { - Logging.logInfo("recreating block colour overrides file %s", f); - BlockColours.writeOverridesFile(f); - if (f.isFile()) { - bc.loadFromFile(f); - } else { - Logging.logError("could not load block colour overrides from file %s", f); - } - } - } - - public void saveBlockColours(BlockColours bc) { - File f = new File(this.configDir, blockColourSaveFileName); - Logging.logInfo("saving block colours to '%s'", f); - bc.saveToFile(f); - } - - public void reloadBlockColours() { - BlockColours bc = new BlockColours(); - File f = new File(this.configDir, blockColourSaveFileName); - if (Config.useSavedBlockColours && f.isFile()) { - // load block colours from file - Logging.logInfo("loading block colours from %s", f); - bc.loadFromFile(f); - this.loadBlockColourOverrides(bc); - } else { - // generate block colours from current texture pack - Logging.logInfo("generating block colours"); - // block type overrides need to be loaded before the block colours are generated - this.loadBlockColourOverrides(bc); - BlockColourGen.genBlockColours(bc); - // load overrides again to override block and biome colours - this.loadBlockColourOverrides(bc); - this.saveBlockColours(bc); - } - this.blockColours = bc; - } - - public void reloadMapTexture() { - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.executor.close(); - MapTexture oldMapTexture = this.mapTexture; - MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); - this.mapTexture = newMapTexture; - if (oldMapTexture != null) { - oldMapTexture.close(); - } - this.executor = new BackgroundExecutor(); - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); - - UndergroundTexture oldTexture = this.undergroundMapTexture; - UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); - this.undergroundMapTexture = newTexture; - if (oldTexture != null) { - this.undergroundMapTexture.close(); - } - } - - public void setCoordsMode(int mode) { - Config.coordsMode = Math.min(Math.max(0, mode), 2); - } - - public int toggleCoords() { - this.setCoordsMode((Config.coordsMode + 1) % 3); - return Config.coordsMode; - } - - public void toggleUndergroundMode() { - Config.undergroundMode = !Config.undergroundMode; - this.miniMap.view.setUndergroundMode(Config.undergroundMode); - } - - public void setServerDetails(String hostname, int port) { - this.serverName = hostname; - this.serverPort = port; - } - - //////////////////////////////// - // Initialization and Cleanup - //////////////////////////////// - - public void load() { - - if (this.ready) { - return; - } - - if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { - Logging.log("Mw.load: world or player is null, cannot load yet"); - return; - } - - Logging.log("Mw.load: loading..."); - - IntegratedServer server = this.mc.getIntegratedServer(); - this.multiplayer = (server == null); - - this.worldName = this.getWorldName(); - - // get world and image directories - File saveDir = this.saveDir; - if (Config.saveDirOverride.length() > 0) { - File d = new File(Config.saveDirOverride); - if (d.isDirectory()) { - saveDir = d; - } else { - Logging.log("error: no such directory %s", Config.saveDirOverride); - } - } - - if (this.multiplayer) { - this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), this.worldName); - } else { - this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), this.worldName); - } - - this.loadWorldConfig(); - - // create directories - this.imageDir = new File(this.worldDir, "images"); - if (!this.imageDir.exists()) { - this.imageDir.mkdirs(); - } - if (!this.imageDir.isDirectory()) { - Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); - } - - this.tickCounter = 0; - - //this.multiplayer = !this.mc.isIntegratedServerRunning(); - - // marker manager only depends on the config being loaded - this.markerManager = new MarkerManager(); - this.markerManager.load(this.worldConfig, catMarkers); - - this.playerTrail = new Trail(this, Reference.PlayerTrailName); - - // executor does not depend on anything - this.executor = new BackgroundExecutor(); - - // mapTexture depends on config being loaded - this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); - this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); - this.reloadBlockColours(); - // region manager depends on config, mapTexture, and block colours - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); - // overlay manager depends on mapTexture - this.miniMap = new MiniMap(this); - this.miniMap.view.setDimension(this.mc.thePlayer.dimension); - - this.chunkManager = new ChunkManager(this); - - this.ready = true; - - //if (!zoomLevelsExist) { - //printBoth("recreating zoom levels"); - //this.regionManager.recreateAllZoomLevels(); - //} - } - - public void close() { - - Logging.log("Mw.close: closing..."); - - if (this.ready) { - this.ready = false; - - this.chunkManager.close(); - this.chunkManager = null; - - // close all loaded regions, saving modified images. - // this will create extra tasks that need to be completed. - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.regionManager = null; - - Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); - if (this.executor.close()) { - Logging.log("error: timeout waiting for tasks to finish"); - } - Logging.log("done"); - - this.playerTrail.close(); - - this.markerManager.save(this.worldConfig, catMarkers); - this.markerManager.clear(); - - // close overlay - this.miniMap.close(); - this.miniMap = null; - - this.undergroundMapTexture.close(); - this.mapTexture.close(); - - this.saveWorldConfig(); - //this.saveConfig(); - - this.tickCounter = 0; - - OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in - } - } - - //////////////////////////////// - // Event handlers - //////////////////////////////// - - public void onTick() { - this.load(); - if (this.ready && (this.mc.thePlayer != null)) { - - this.updatePlayer(); - - if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { - this.undergroundMapTexture.update(); - } - - if (!(this.mc.currentScreen instanceof MwGui)) { - // if in game (no gui screen) center the minimap on the player and render it. - this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); - this.miniMap.drawCurrentMap(); - } - - // process background tasks - int maxTasks = 50; - while (!this.executor.processTaskQueue() && (maxTasks > 0)) { - maxTasks--; - } - - this.chunkManager.onTick(); - - // update GL texture of mapTexture if updated - this.mapTexture.processTextureUpdates(); - - // let the renderEngine know we have changed the bound texture. - //this.mc.renderEngine.resetBoundTexture(); - - //if (this.tickCounter % 100 == 0) { - // MwUtil.log("tick %d", this.tickCounter); - //} - this.playerTrail.onTick(); - - this.tickCounter++; - } - } - - // add chunk to the set of loaded chunks - public void onChunkLoad(Chunk chunk) { - this.load(); - if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - if (this.ready) { - this.chunkManager.addChunk(chunk); - } else { - Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); - } - } - } - - // remove chunk from the set of loaded chunks. - // convert to mwchunk and write chunk to region file if in multiplayer. - public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - this.chunkManager.removeChunk(chunk); - } - } - - // from onTick when mc.currentScreen is an instance of GuiGameOver - // it's the only option to detect death client side - public void onPlayerDeath(EntityPlayerMP player) { - if (this.ready && (Config.maxDeathMarkers > 0)) { - this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; - for (int i = 0; i < deleteCount; i++) { - // delete the first marker found in the group "playerDeaths". - // as new markers are only ever appended to the marker list this will delete the - // earliest death marker added. - this.markerManager.delMarker(null, "playerDeaths"); - } - - this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); - this.markerManager.setVisibleGroupName("playerDeaths"); - this.markerManager.update(); - } - } - - public void onKeyDown(KeyBinding kb) { - // make sure not in GUI element (e.g. chat box) - if ((this.mc.currentScreen == null) && (this.ready)) { - //Mw.log("client tick: %s key pressed", kb.keyDescription); - - if (kb == MwKeyHandler.keyMapMode) { - // map mode toggle - this.miniMap.nextOverlayMode(1); - - } else if (kb == MwKeyHandler.keyMapGui) { - // open map gui - this.mc.displayGuiScreen(new MwGui(this)); - - } else if (kb == MwKeyHandler.keyNewMarker) { - // open new marker dialog - String group = this.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - - } else if (kb == MwKeyHandler.keyNextGroup) { - // toggle marker mode - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - - } else if (kb == MwKeyHandler.keyTeleport) { - // set or remove marker - Marker marker = this.markerManager.getNearestMarkerInDirection( - this.playerXInt, - this.playerZInt, - this.playerHeading); - if (marker != null) { - this.teleportToMarker(marker); - } - } else if (kb == MwKeyHandler.keyZoomIn) { - // zoom in - this.miniMap.view.adjustZoomLevel(-1); - } else if (kb == MwKeyHandler.keyZoomOut) { - // zoom out - this.miniMap.view.adjustZoomLevel(1); - } else if (kb == MwKeyHandler.keyUndergroundMode) { - this.toggleUndergroundMode(); - } - } - } -} +package mapwriter; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.forge.MwForge; +import mapwriter.forge.MwKeyHandler; +import mapwriter.gui.MwGui; +import mapwriter.gui.MwGuiMarkerDialog; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.MapTexture; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.map.MiniMap; +import mapwriter.map.Trail; +import mapwriter.map.UndergroundTexture; +import mapwriter.overlay.OverlaySlime; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; +import mapwriter.tasks.CloseRegionManagerTask; +import mapwriter.util.Config; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Render; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.config.Configuration; + +public class Mw { + public Minecraft mc = null; + + // configuration files (global and world specific) + public static Configuration worldConfig = null; + + // server information + public String worldName = "default"; + private String serverName = "default"; + private int serverPort = 0; + + // directories + private final File configDir; + private final File saveDir; + public File worldDir = null; + public File imageDir = null; + + // flags and counters + public boolean ready = false; + public boolean multiplayer = false; + public int tickCounter = 0; + + // list of available dimensions + public List dimensionList = new ArrayList(); + + // player position and heading + public double playerX = 0.0; + public double playerZ = 0.0; + public double playerY = 0.0; + public int playerXInt = 0; + public int playerYInt = 0; + public int playerZInt = 0; + public double playerHeading = 0.0; + public int playerDimension = 0; + public double mapRotationDegrees = 0.0; + + // constants + public final static String catWorld = "world"; + public final static String catMarkers = "markers"; + public final static String worldDirConfigName = "mapwriter.cfg"; + public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + // instances of components + public MapTexture mapTexture = null; + public UndergroundTexture undergroundMapTexture = null; + public BackgroundExecutor executor = null; + public MiniMap miniMap = null; + public MarkerManager markerManager = null; + public BlockColours blockColours = null; + public RegionManager regionManager = null; + public ChunkManager chunkManager = null; + public Trail playerTrail = null; + + public static Mw instance; + + public Mw() { + // client only initialization + this.mc = Minecraft.getMinecraft(); + + // create base save directory + this.saveDir = new File(this.mc.mcDataDir, "saves"); + this.configDir = new File(this.mc.mcDataDir, "config"); + + this.ready = false; + + RegionManager.logger = MwForge.logger; + + instance = this; + + ConfigurationHandler.loadConfig(); + } + + public String getWorldName() { + String worldName; + if (this.multiplayer) { + if (Config.portNumberInWorldNameEnabled) { + worldName = String.format("%s_%d", this.serverName, this.serverPort); + } else { + worldName = String.format("%s", this.serverName); + } + + } else { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = this.mc.getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = Utils.mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } + + public void loadWorldConfig() { + // load world specific config file + File worldConfigFile = new File(this.worldDir, worldDirConfigName); + this.worldConfig = new Configuration(worldConfigFile); + this.worldConfig.load(); + + this.dimensionList.clear(); + this.worldConfig.get(catWorld, "dimensionList", Utils.integerListToIntArray(this.dimensionList)); + this.addDimension(0); + this.cleanDimensionList(); + } + + public void saveWorldConfig() { + //this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); + this.worldConfig.save(); + } + + public void setTextureSize() { + if (Config.configTextureSize != Config.textureSize) { + int maxTextureSize = Render.getMaxTextureSize(); + int textureSize = 1024; + while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { + textureSize *= 2; + } + textureSize /= 2; + + Logging.log("GL reported max texture size = %d", maxTextureSize); + Logging.log("texture size from config = %d", Config.configTextureSize); + Logging.log("setting map texture size to = %d", textureSize); + + Config.textureSize = textureSize; + if (this.ready) { + // if we are already up and running need to close and reinitialize the map texture and + // region manager. + this.reloadMapTexture(); + } + } + } + + // update the saved player position and orientation + // called every tick + public void updatePlayer() { + // get player pos + this.playerX = (double) this.mc.thePlayer.posX; + this.playerY = (double) this.mc.thePlayer.posY; + this.playerZ = (double) this.mc.thePlayer.posZ; + this.playerXInt = (int) Math.floor(this.playerX); + this.playerYInt = (int) Math.floor(this.playerY); + this.playerZInt = (int) Math.floor(this.playerZ); + + // rotationYaw of 0 points due north, we want it to point due east instead + // so add pi/2 radians (90 degrees) + this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); + this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; + + // set by onWorldLoad + this.playerDimension = this.mc.theWorld.provider.getDimensionId(); + if (this.miniMap.view.getDimension() != this.playerDimension) + { + this.addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); + } + } + + public void addDimension(int dimension) { + int i = this.dimensionList.indexOf(dimension); + if (i < 0) { + this.dimensionList.add(dimension); + } + } + + public void cleanDimensionList() { + List dimensionListCopy = new ArrayList(this.dimensionList); + this.dimensionList.clear(); + for (int dimension : dimensionListCopy) { + this.addDimension(dimension); + } + } + + public void toggleMarkerMode() { + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + } + + // cheap and lazy way to teleport... + public void teleportTo(int x, int y, int z) { + if (Config.teleportEnabled) { + this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void warpTo(String name) { + if (Config.teleportEnabled) { + //MwUtil.printBoth(String.format("warping to %s", name)); + this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void teleportToMapPos(MapView mapView, int x, int y, int z) { + if (!Config.teleportCommand.equals("warp")) { + double scale = mapView.getDimensionScaling(this.playerDimension); + this.teleportTo((int) (x / scale), y, (int) (z / scale)); + } else { + Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); + } + } + + public void teleportToMarker(Marker marker) { + if (Config.teleportCommand.equals("warp")) { + this.warpTo(marker.name); + } else if (marker.dimension == this.playerDimension) { + this.teleportTo(marker.x, marker.y, marker.z); + } else { + Utils.printBoth("cannot teleport to marker in different dimension"); + } + } + + public void loadBlockColourOverrides(BlockColours bc) { + File f = new File(this.configDir, blockColourOverridesFileName); + if (f.isFile()) { + Logging.logInfo("loading block colour overrides file %s", f); + bc.loadFromFile(f); + } else { + Logging.logInfo("recreating block colour overrides file %s", f); + BlockColours.writeOverridesFile(f); + if (f.isFile()) { + bc.loadFromFile(f); + } else { + Logging.logError("could not load block colour overrides from file %s", f); + } + } + } + + public void saveBlockColours(BlockColours bc) { + File f = new File(this.configDir, blockColourSaveFileName); + Logging.logInfo("saving block colours to '%s'", f); + bc.saveToFile(f); + } + + public void reloadBlockColours() { + BlockColours bc = new BlockColours(); + File f = new File(this.configDir, blockColourSaveFileName); + if (Config.useSavedBlockColours && f.isFile()) { + // load block colours from file + Logging.logInfo("loading block colours from %s", f); + bc.loadFromFile(f); + this.loadBlockColourOverrides(bc); + } else { + // generate block colours from current texture pack + Logging.logInfo("generating block colours"); + // block type overrides need to be loaded before the block colours are generated + this.loadBlockColourOverrides(bc); + BlockColourGen.genBlockColours(bc); + // load overrides again to override block and biome colours + this.loadBlockColourOverrides(bc); + this.saveBlockColours(bc); + } + this.blockColours = bc; + } + + public void reloadMapTexture() { + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.executor.close(); + MapTexture oldMapTexture = this.mapTexture; + MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); + this.mapTexture = newMapTexture; + if (oldMapTexture != null) { + oldMapTexture.close(); + } + this.executor = new BackgroundExecutor(); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); + + UndergroundTexture oldTexture = this.undergroundMapTexture; + UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); + this.undergroundMapTexture = newTexture; + if (oldTexture != null) { + this.undergroundMapTexture.close(); + } + } + + public void toggleUndergroundMode() { + Config.undergroundMode = !Config.undergroundMode; + this.miniMap.view.setUndergroundMode(Config.undergroundMode); + } + + public void setServerDetails(String hostname, int port) { + this.serverName = hostname; + this.serverPort = port; + } + + //////////////////////////////// + // Initialization and Cleanup + //////////////////////////////// + + public void load() { + + if (this.ready) { + return; + } + + if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { + Logging.log("Mw.load: world or player is null, cannot load yet"); + return; + } + + Logging.log("Mw.load: loading..."); + + IntegratedServer server = this.mc.getIntegratedServer(); + this.multiplayer = (server == null); + + this.worldName = this.getWorldName(); + + // get world and image directories + File saveDir = this.saveDir; + if (Config.saveDirOverride.length() > 0) { + File d = new File(Config.saveDirOverride); + if (d.isDirectory()) { + saveDir = d; + } else { + Logging.log("error: no such directory %s", Config.saveDirOverride); + } + } + + if (this.multiplayer) { + this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), this.worldName); + } else { + this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), this.worldName); + } + + this.loadWorldConfig(); + + // create directories + this.imageDir = new File(this.worldDir, "images"); + if (!this.imageDir.exists()) { + this.imageDir.mkdirs(); + } + if (!this.imageDir.isDirectory()) { + Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); + } + + this.tickCounter = 0; + + //this.multiplayer = !this.mc.isIntegratedServerRunning(); + + // marker manager only depends on the config being loaded + this.markerManager = new MarkerManager(); + this.markerManager.load(this.worldConfig, catMarkers); + + this.playerTrail = new Trail(this, Reference.PlayerTrailName); + + // executor does not depend on anything + this.executor = new BackgroundExecutor(); + + // mapTexture depends on config being loaded + this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); + this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); + this.reloadBlockColours(); + // region manager depends on config, mapTexture, and block colours + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); + // overlay manager depends on mapTexture + this.miniMap = new MiniMap(this); + this.miniMap.view.setDimension(this.mc.thePlayer.dimension); + + this.chunkManager = new ChunkManager(this); + + this.ready = true; + + //if (!zoomLevelsExist) { + //printBoth("recreating zoom levels"); + //this.regionManager.recreateAllZoomLevels(); + //} + } + + public void close() { + + Logging.log("Mw.close: closing..."); + + if (this.ready) { + this.ready = false; + + this.chunkManager.close(); + this.chunkManager = null; + + // close all loaded regions, saving modified images. + // this will create extra tasks that need to be completed. + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.regionManager = null; + + Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); + if (this.executor.close()) { + Logging.log("error: timeout waiting for tasks to finish"); + } + Logging.log("done"); + + this.playerTrail.close(); + + this.markerManager.save(this.worldConfig, catMarkers); + this.markerManager.clear(); + + // close overlay + this.miniMap.close(); + this.miniMap = null; + + this.undergroundMapTexture.close(); + this.mapTexture.close(); + + this.saveWorldConfig(); + //this.saveConfig(); + + this.tickCounter = 0; + + OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in + } + } + + //////////////////////////////// + // Event handlers + //////////////////////////////// + + public void onTick() { + this.load(); + if (this.ready && (this.mc.thePlayer != null)) { + + this.updatePlayer(); + + if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { + this.undergroundMapTexture.update(); + } + + if (!(this.mc.currentScreen instanceof MwGui)) { + // if in game (no gui screen) center the minimap on the player and render it. + this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); + this.miniMap.drawCurrentMap(); + } + + // process background tasks + int maxTasks = 50; + while (!this.executor.processTaskQueue() && (maxTasks > 0)) { + maxTasks--; + } + + this.chunkManager.onTick(); + + // update GL texture of mapTexture if updated + this.mapTexture.processTextureUpdates(); + + // let the renderEngine know we have changed the bound texture. + //this.mc.renderEngine.resetBoundTexture(); + + //if (this.tickCounter % 100 == 0) { + // MwUtil.log("tick %d", this.tickCounter); + //} + this.playerTrail.onTick(); + + this.tickCounter++; + } + } + + // add chunk to the set of loaded chunks + public void onChunkLoad(Chunk chunk) { + this.load(); + if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + if (this.ready) { + this.chunkManager.addChunk(chunk); + } else { + Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); + } + } + } + + // remove chunk from the set of loaded chunks. + // convert to mwchunk and write chunk to region file if in multiplayer. + public void onChunkUnload(Chunk chunk) { + if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + this.chunkManager.removeChunk(chunk); + } + } + + // from onTick when mc.currentScreen is an instance of GuiGameOver + // it's the only option to detect death client side + public void onPlayerDeath(EntityPlayerMP player) { + if (this.ready && (Config.maxDeathMarkers > 0)) { + this.updatePlayer(); + int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; + for (int i = 0; i < deleteCount; i++) { + // delete the first marker found in the group "playerDeaths". + // as new markers are only ever appended to the marker list this will delete the + // earliest death marker added. + this.markerManager.delMarker(null, "playerDeaths"); + } + + this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); + this.markerManager.setVisibleGroupName("playerDeaths"); + this.markerManager.update(); + } + } + + public void onKeyDown(KeyBinding kb) { + // make sure not in GUI element (e.g. chat box) + if ((this.mc.currentScreen == null) && (this.ready)) { + //Mw.log("client tick: %s key pressed", kb.keyDescription); + + if (kb == MwKeyHandler.keyMapMode) { + // map mode toggle + this.miniMap.nextOverlayMode(1); + + } else if (kb == MwKeyHandler.keyMapGui) { + // open map gui + this.mc.displayGuiScreen(new MwGui(this)); + + } else if (kb == MwKeyHandler.keyNewMarker) { + // open new marker dialog + String group = this.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + null, + this.markerManager, + "", + group, + this.playerXInt, + this.playerYInt, + this.playerZInt, + this.playerDimension + ) + ); + + } else if (kb == MwKeyHandler.keyNextGroup) { + // toggle marker mode + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + + } else if (kb == MwKeyHandler.keyTeleport) { + // set or remove marker + Marker marker = this.markerManager.getNearestMarkerInDirection( + this.playerXInt, + this.playerZInt, + this.playerHeading); + if (marker != null) { + this.teleportToMarker(marker); + } + } else if (kb == MwKeyHandler.keyZoomIn) { + // zoom in + this.miniMap.view.adjustZoomLevel(-1); + } else if (kb == MwKeyHandler.keyZoomOut) { + // zoom out + this.miniMap.view.adjustZoomLevel(1); + } else if (kb == MwKeyHandler.keyUndergroundMode) { + this.toggleUndergroundMode(); + } + } + } +} diff --git a/src/main/java/mapwriter/api/package-info.java b/src/main/java/mapwriter/api/package-info.java new file mode 100644 index 00000000..f7a37dd7 --- /dev/null +++ b/src/main/java/mapwriter/api/package-info.java @@ -0,0 +1,6 @@ + +@API(owner = "MapWriter", provides = "MapWriterApi", + apiVersion = "1.0.0") package mapwriter.api; + +import net.minecraftforge.fml.common.API; + diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index c56d3c09..e731fae4 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -2,33 +2,162 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Config; import mapwriter.util.Reference; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.AddModOverrideEntry; +import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.ModOverridesEntry; +import net.minecraftforge.common.ForgeChunkManager; +import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.GuiConfigEntries; +import net.minecraftforge.fml.client.config.GuiUtils; +import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; import net.minecraftforge.fml.client.config.IConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.CategoryEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.NumberSliderEntry; public class ModGuiConfig extends GuiConfig { public ModGuiConfig(GuiScreen guiScreen) { super(guiScreen, - new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + getConfigElements(), + //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), Reference.MOD_ID, + "Options", false, false, GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); } - private static List getConfigElements() + /** Compiles a list of config elements */ + private static List getConfigElements() { - List list = new ArrayList(); - - return list; + List list = new ArrayList(); + + //Add categories to config GUI + list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); + list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); + list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); + list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); + return list; } + + /** Creates a button linking to another screen where all options of the category are available */ + private static IConfigElement categoryElement(String category, String name, String tooltip_key) + { + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); + } + + public static class ModBooleanEntry extends ButtonEntry + { + protected final boolean beforeValue; + protected boolean currentValue; + + public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) + { + super(owningScreen, owningEntryList, configElement); + this.beforeValue = Boolean.valueOf(configElement.get().toString()); + this.currentValue = beforeValue; + this.btnValue.enabled = enabled(); + updateValueButtonText(); + } + + @Override + public void updateValueButtonText() + { + this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); + btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); + } + + @Override + public void valueButtonPressed(int slotIndex) + { + if (enabled()) + currentValue = !currentValue; + } + + @Override + public boolean isDefault() + { + return currentValue == Boolean.valueOf(configElement.getDefault().toString()); + } + + @Override + public void setToDefault() + { + if (enabled()) + { + currentValue = Boolean.valueOf(configElement.getDefault().toString()); + updateValueButtonText(); + } + } + @Override + public boolean isChanged() + { + return currentValue != beforeValue; + } + + @Override + public void undoChanges() + { + if (enabled()) + { + currentValue = beforeValue; + updateValueButtonText(); + } + } + + @Override + public boolean saveConfigElement() + { + if (enabled() && isChanged()) + { + configElement.set(currentValue); + return configElement.requiresMcRestart(); + } + return false; + } + + @Override + public Boolean getCurrentValue() + { + return currentValue; + } + + @Override + public Boolean[] getCurrentValues() + { + return new Boolean[] { getCurrentValue() }; + } + + @Override + public boolean enabled() + { + for (IConfigEntry entry : this.owningEntryList.listEntries) + { + if (entry.getName().equals("circular") && entry instanceof BooleanEntry) + { + return Boolean.valueOf(entry.getCurrentValue().toString()); + } + } + + return true; + } + } } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 65cb979d..352e2a70 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,645 +1,646 @@ -package mapwriter.gui; - -import java.awt.Point; -import java.io.IOException; - -import mapwriter.Mw; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import mapwriter.util.Config; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.util.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - //private int mouseRightHeld = 0; - //private int mouseMiddleHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - - class Label { - int x = 0, y = 0, w = 1, h = 12; - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); - } - } - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - this.mapView.setZoomLevel(0); - - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - } - - public MwGui(Mw mw, int dim, int x, int z){ - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(0); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - public void exitGui() { - //MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - this.mapMode.close(); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); - this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), - (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension(), - this.mw.worldDir, - this.mw.worldDir.getName())); - - Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); - } - - public void regenerateView() { - Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ())); - this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask( - this.mw, - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch(key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, - 0 - ); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen( - new MwGuiTeleportDialog( - this, - this.mw, - this.mapView, - this.mouseBlockX, - Config.defaultTeleportHeight, - this.mouseBlockZ - ) - ); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - //case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(Config.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) - { - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen( - new MwGuiDimensionDialog( - this, - this.mw, - this.mapView, - this.mapView.getDimension() - ) - ); - } else if (this.optionsLabel.posWithin(x, y)) - { - try - { - GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); - this.mc.displayGuiScreen(newScreen); - } - catch (Exception e) - { - Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); - } - - //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - //this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - marker - ) - ); - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - //this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { - //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - //this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(this.mw.dimensionList, n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); - } - } - - // called every frame - public void updateScreen() { - //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) { - String s; - if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); - } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); - } - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { - s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); - } - } - - /*if (this.mw.markerManager.selectedMarker != null) { - s += ", current marker: " + this.mw.markerManager.selectedMarker.name; - }*/ - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); - this.drawCenteredString(this.fontRendererObj, - s, this.width / 2, this.height - 18, 0xffffff); - } - - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max( - this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, - title, - x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, - desc, - x + 10, y + 4, 0xcccccc); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - //double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - //this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); - } - - super.drawScreen(mouseX, mouseY, f); - } -} - +package mapwriter.gui; + +import java.awt.Point; +import java.io.IOException; + +import mapwriter.Mw; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Config; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + public MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private int exit = 0; + + private Label helpLabel; + private Label optionsLabel; + private Label dimensionLabel; + private Label groupLabel; + private Label overlayLabel; + + public static MwGui instance; + + class Label { + int x = 0, y = 0, w = 1, h = 12; + public Label() { + } + + public void draw(int x, int y, String s) { + this.x = x; + this.y = y; + this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; + MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); + MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); + } + + public void drawToRightOf(Label label, String s) { + this.draw(label.x + label.w + 5, label.y, s); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); + } + } + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(); + this.mapView = new MapView(this.mw); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + this.mapView.setZoomLevel(0); + + this.helpLabel = new Label(); + this.optionsLabel = new Label(); + this.dimensionLabel = new Label(); + this.groupLabel = new Label(); + this.overlayLabel = new Label(); + + instance = this; + } + + public MwGui(Mw mw, int dim, int x, int z){ + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(0); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() { + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) { + + } + + public void exitGui() { + //MwUtil.log("closing GUI"); + // set the mini map dimension to the GUI map dimension when closing + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + this.mc.getSoundHandler().resumeSounds(); + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); + if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); + this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), + (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension(), + this.mw.worldDir, + this.mw.worldDir.getName())); + + Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); + } + + public void regenerateView() { + Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ())); + this.mw.reloadBlockColours(); + this.mw.executor.addTask2(new RebuildRegionsTask( + this.mw, + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch(key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, + 0 + ); + } + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen( + new MwGuiTeleportDialog( + this, + this.mw, + this.mapView, + this.mouseBlockX, + Config.defaultTeleportHeight, + this.mouseBlockZ + ) + ); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + //case Keyboard.KEY_9: + // MwUtil.log("refreshing maptexture"); + // this.mw.mapTexture.updateTexture(); + // break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + // exit on the next tick + this.exit = 1; + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(Config.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) + return; + + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) + { + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen( + new MwGuiDimensionDialog( + this, + this.mw, + this.mapView, + this.mapView.getDimension() + ) + ); + } else if (this.optionsLabel.posWithin(x, y)) + { + try + { + GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } + catch (Exception e) + { + Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); + } + + //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + //this.mouseRightHeld = 1; + if ((marker != null) && (prevMarker == marker)) { + // right clicked previously selected marker. + // edit the marker + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + marker + ) + ); + + } else if (marker == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(x, y)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + "", + group, + mx, my, mz, + this.mapView.getDimension() + ) + ); + } + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + //this.viewSizeStart = this.mapManager.getViewSize(); + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseReleased(int x, int y, int button) { + //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + //this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(this.mw.dimensionList, n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); + } + } + + // called every frame + public void updateScreen() { + //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); + // need to wait one tick before exiting so that the game doesn't + // handle the 'm' key and re-open the gui. + // there should be a better way. + if (this.exit > 0) { + this.exit++; + } + if (this.exit > 2) { + this.exitGui(); + } + super.updateScreen(); + } + + public void drawStatus(int bX, int bY, int bZ) { + String s; + if (bY != 0) { + s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + } else { + s = String.format("cursor: (%d, ?, %d)", bX, bZ); + } + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { + s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); + } + } + + /*if (this.mw.markerManager.selectedMarker != null) { + s += ", current marker: " + this.mw.markerManager.selectedMarker.name; + }*/ + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); + + drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); + this.drawCenteredString(this.fontRendererObj, + s, this.width / 2, this.height - 18, 0xffffff); + } + + public void drawHelp() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString( + "Keys:\n\n" + + " Space\n" + + " Delete\n" + + " C\n" + + " Home\n" + + " End\n" + + " N\n" + + " T\n" + + " P\n" + + " R\n" + + " U\n\n" + + "Left click drag or arrow keys pan the map.\n" + + "Mouse wheel or Page Up/Down zooms map.\n" + + "Right click map to create a new marker.\n" + + "Left click drag a selected marker to move it.\n" + + "Mouse wheel over selected marker to cycle colour.\n" + + "Mouse wheel over dimension or group box to cycle.\n", + 15, 24, this.width - 30, 0xffffff); + this.fontRendererObj.drawSplitString( + "| Next marker group\n" + + "| Delete selected marker\n" + + "| Cycle selected marker colour\n" + + "| Centre map on player\n" + + "| Centre map on selected marker\n" + + "| Select next marker\n" + + "| Teleport to cursor or selected marker\n" + + "| Save PNG of visible map area\n" + + "| Regenerate visible map area from region files\n" + + "| Underground map mode\n", + 75, 42, this.width - 90, 0xffffff); + } + + public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { + String desc = String.format("(%d, %d, %d)", mX, mY, mZ); + int stringW = Math.max( + this.fontRendererObj.getStringWidth(title), + this.fontRendererObj.getStringWidth(desc)); + + x = Math.min(x, this.width - (stringW + 16)); + y = Math.min(Math.max(10, y), this.height - 14); + + drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); + this.drawString(this.fontRendererObj, + title, + x + 10, y - 8, 0xffffff); + this.drawString(this.fontRendererObj, + desc, + x + 10, y + 4, 0xcccccc); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + //double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + //this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(menuX, menuY, "[help]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); + String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + this.drawHelp(); + } + + super.drawScreen(mouseX, mouseY, f); + } +} + diff --git a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java deleted file mode 100644 index a769d4e5..00000000 --- a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java +++ /dev/null @@ -1,232 +0,0 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import mapwriter.util.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiSlot; -import net.minecraft.util.ResourceLocation; - -public class MwGuiOptionSlot extends GuiSlot { - - //private GuiScreen parentScreen; - private Minecraft mc; - private Mw mw; - - private int mouseX = 0; - private int mouseY = 0; - - private int miniMapPositionIndex = 0; - private static final String[] miniMapPositionStringArray = { - "unchanged", - "top right", - "top left", - "bottom right", - "bottom left" - }; - private static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; - private static final String[] backgroundModeStringArray = { - "none", - "static", - "panning" - }; - - private GuiButton[] buttons = new GuiButton[12]; - - static final ResourceLocation WIDGET_TEXTURE_LOC = new ResourceLocation("textures/gui/widgets.png"); - - public void updateButtonLabel(int i) { - switch(i) { - case 0: - this.buttons[i].displayString = "Draw coords: " + coordsModeStringArray[Config.coordsMode]; - break; - case 1: - this.buttons[i].displayString = "Circular mode: " + this.mw.miniMap.smallMapMode.circular; - break; - case 2: - this.buttons[i].displayString = "Texture size: " + Config.configTextureSize; - break; - case 3: - this.buttons[i].displayString = "Texture scaling: " + (Config.linearTextureScalingEnabled ? "linear" : "nearest"); - break; - case 4: - this.buttons[i].displayString = "Trail markers: " + (this.mw.playerTrail.enabled); - break; - case 5: - this.buttons[i].displayString = "Map colours: " + (Config.useSavedBlockColours ? "frozen" : "auto"); - break; - case 6: - this.buttons[i].displayString = "Max draw distance: " + Math.round(Math.sqrt(Config.maxChunkSaveDistSq)); - break; - case 7: - this.buttons[i].displayString = "Mini map size: " + this.mw.miniMap.smallMapMode.heightPercent; - break; - case 8: - this.buttons[i].displayString = "Mini map position: " + miniMapPositionStringArray[this.miniMapPositionIndex]; - break; - case 9: - this.buttons[i].displayString = "Map pixel snapping: " + (Config.mapPixelSnapEnabled ? "enabled" : "disabled"); - break; - case 10: - this.buttons[i].displayString = "Max death markers: " + Config.maxDeathMarkers; - break; - case 11: - this.buttons[i].displayString = "Background mode: " + backgroundModeStringArray[Config.backgroundTextureMode]; - break; - //case 11: - // this.buttons[i].displayString = "Map Lighting: " + (this.mw.lightingEnabled ? "enabled" : "disabled"); - // break; - default: - break; - } - } - - public MwGuiOptionSlot(GuiScreen parentScreen, Minecraft mc, Mw mw) { - // GuiSlot(minecraft, width, height, top, bottom, slotHeight) - super(mc, parentScreen.width, parentScreen.height, 16, parentScreen.height - 32, 25); - //this.parentScreen = parentScreen; - this.mw = mw; - this.mc = mc; - for (int i = 0; i < this.buttons.length; i++) { - this.buttons[i] = new GuiButton(300 + i, 0, 0, ""); - this.updateButtonLabel(i); - } - } - - protected boolean keyTyped(char c, int k) { - return false; - } - - @Override - protected int getSize() { - // number of slots - return this.buttons.length; - } - - @Override - protected void elementClicked(int i, boolean doubleClicked, int x, int y) { - switch(i) { - case 0: - // toggle coords - this.mw.toggleCoords(); - break; - case 1: - // toggle circular - this.mw.miniMap.toggleRotating(); - break; - case 2: - // toggle texture size - Config.configTextureSize *= 2; - if (Config.configTextureSize > 4096) { - Config.configTextureSize = 1024; - } - break; - case 3: - // linear scaling - Config.linearTextureScalingEnabled = !Config.linearTextureScalingEnabled; - this.mw.mapTexture.setLinearScaling(Config.linearTextureScalingEnabled); - //this.mw.undergroundMapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); - break; - case 4: - // player trail - this.mw.playerTrail.enabled = !this.mw.playerTrail.enabled; - break; - case 5: - // map colours - Config.useSavedBlockColours = !Config.useSavedBlockColours; - // reload block colours before saving in case player changed - // texture packs before pressing button. - this.mw.reloadBlockColours(); - break; - case 6: - // toggle max chunk save dist - int d = Math.round((float) Math.sqrt(Config.maxChunkSaveDistSq)); - d += 32; - if (d > 256) { - d = 64; - } - Config.maxChunkSaveDistSq = d * d; - break; - case 7: - this.mw.miniMap.smallMapMode.toggleHeightPercent(); - break; - case 8: - this.miniMapPositionIndex++; - if (this.miniMapPositionIndex >= miniMapPositionStringArray.length) { - // don't go back to the "unchanged" setting - this.miniMapPositionIndex = 1; - } - switch (this.miniMapPositionIndex) { - case 1: - // top right position - this.mw.miniMap.smallMapMode.setMargins(10, -1, -1, 10); - break; - case 2: - // top left position - this.mw.miniMap.smallMapMode.setMargins(10, -1, 10, -1); - break; - case 3: - // bottom right position - this.mw.miniMap.smallMapMode.setMargins(-1, 40, -1, 10); - break; - case 4: - // bottom left position - this.mw.miniMap.smallMapMode.setMargins(-1, 40, 10, -1); - break; - default: - break; - } - case 9: - // map scroll pixel snapping - Config.mapPixelSnapEnabled = !Config.mapPixelSnapEnabled; - break; - case 10: - // max death markers - Config.maxDeathMarkers++; - if (Config.maxDeathMarkers > 10) { - Config.maxDeathMarkers = 0; - } - break; - case 11: - // background texture mode - Config.backgroundTextureMode = (Config.backgroundTextureMode + 1) % 3; - break; - //case 11: - // // lighting - // this.mw.lightingEnabled = !this.mw.lightingEnabled; - // break; - default: - break; - } - this.updateButtonLabel(i); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float f) { - this.mouseX = mouseX; - this.mouseY = mouseY; - super.drawScreen(mouseX, mouseY, f); - } - - @Override - protected boolean isSelected(int i) { - return false; - } - - @Override - protected void drawBackground() { - } - - @Override - protected void drawSlot(int i, int x, int y, int i4, int i5, int i6){ - GuiButton button = buttons[i]; - button.xPosition = x; - button.yPosition = y; - button.drawButton(this.mc, this.mouseX, this.mouseY); - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiOptions.java b/src/main/java/mapwriter/gui/MwGuiOptions.java deleted file mode 100644 index ad02dd0f..00000000 --- a/src/main/java/mapwriter/gui/MwGuiOptions.java +++ /dev/null @@ -1,63 +0,0 @@ -package mapwriter.gui; - -import java.io.IOException; - -import mapwriter.Mw; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; - -public class MwGuiOptions extends GuiScreen { - - private final Mw mw; - private final GuiScreen parentScreen; - private MwGuiOptionSlot optionSlot = null; - - public MwGuiOptions(GuiScreen parentScreen, Mw mw) { - this.mw = mw; - this.parentScreen = parentScreen; - } - - @SuppressWarnings("unchecked") - public void initGui() { - this.optionSlot = new MwGuiOptionSlot(this, this.mc, this.mw); - this.optionSlot.registerScrollButtons(7, 8); - - this.buttonList.add(new GuiButton(200, (this.width / 2) - 50, this.height - 28, 100, 20, "Done")); - } - - protected void actionPerformed(GuiButton button) { - if (button.id == 200) { - // done - // reconfigure texture size - this.mw.setTextureSize(); - this.mc.displayGuiScreen(this.parentScreen); - } - } - - public void drawScreen(int mouseX, int mouseY, float f) { - this.drawDefaultBackground(); - this.optionSlot.drawScreen(mouseX, mouseY, f); - this.drawCenteredString(this.fontRendererObj, "MapWriter Options", this.width / 2, 10, 0xffffff); - super.drawScreen(mouseX, mouseY, f); - } - - public void handleMouseInput() throws IOException - { - if (this.optionSlot != null) - { - this.optionSlot.handleMouseInput(); - } - super.handleMouseInput(); - } - - protected void mouseClicked(int x, int y, int button) throws IOException { - super.mouseClicked(x, y, button); - } - - - protected void keyTyped(char c, int k) throws IOException { - if (this.optionSlot.keyTyped(c, k)) { - super.keyTyped(c, k); - } - } -} diff --git a/src/main/java/mapwriter/handler/ConfigurationHandler.java b/src/main/java/mapwriter/handler/ConfigurationHandler.java index 507f48d5..065527b8 100644 --- a/src/main/java/mapwriter/handler/ConfigurationHandler.java +++ b/src/main/java/mapwriter/handler/ConfigurationHandler.java @@ -2,7 +2,6 @@ import java.io.File; -import mapwriter.Mw; import mapwriter.util.Config; import mapwriter.util.Reference; import net.minecraftforge.common.config.Configuration; @@ -19,18 +18,18 @@ public static void init(File configFile) if (configuration == null) { configuration = new Configuration(configFile); + setMapModeDefaults(); loadConfig(); } } public static void loadConfig() { - configuration.load(); Config.linearTextureScalingEnabled = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingEnabled, ""); Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, ""); Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, ""); Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, ""); - Config.coordsMode = configuration.getInt("coordsMode", Reference.catOptions, Config.coordsMode, 0, 2, ""); + Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "", Config.coordsModeStringArray); Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, ""); Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, ""); Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, ""); @@ -45,13 +44,17 @@ public static void loadConfig() Config.maxZoom = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.maxZoom, 1, 256, ""); Config.minZoom = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.minZoom, 1, 256, ""); - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 8192, ""); + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, ""); - if (configuration.hasChanged()) + Config.fullScreenMap.loadConfig(); + Config.largeMap.loadConfig(); + Config.smallMap.loadConfig(); + + if (configuration.hasChanged()) { configuration.save(); } - + //Mw.instance.setTextureSize(); } @@ -61,18 +64,7 @@ public static void loadWorldConfig() Config.modeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.modeIndex, 0, 1000, ""); Config.zoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.minZoom, Config.maxZoom, ""); } - - public static void SaveConfig() - { - //this.mw.config.setInt(Reference.catOptions, "overlayModeIndex", Config.modeIndex); - //this.mw.config.setInt(Reference.catOptions, "overlayZoomLevel", this.view.getZoomLevel()); - - //this.mw.config.setBoolean(Reference.catOptions, Reference.TrailName + "TrailEnabled", Config.PlayerTrailEnabled); - //this.mw.config.setInt(Reference.catOptions, Reference.TrailName + "TrailMaxLength", Config.maxLength); - //this.mw.config.setInt(Reference.catOptions, Reference.TrailName + "TrailMarkerIntervalMillis", (int) Config.intervalMillis); - } - @SubscribeEvent public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { @@ -81,4 +73,49 @@ public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent loadConfig(); } } - } + + public static void setMapModeDefaults() + { + Config.fullScreenMap.heightPercent = -1; + Config.fullScreenMap.marginTop = 0; + Config.fullScreenMap.marginBottom = 0; + Config.fullScreenMap.marginLeft = 0; + Config.fullScreenMap.marginRight = 0; + Config.fullScreenMap.borderMode = 0; + Config.fullScreenMap.playerArrowSize = 5; + Config.fullScreenMap.markerSize = 5; + Config.fullScreenMap.alphaPercent = 100; + Config.fullScreenMap.rotate = false; + Config.fullScreenMap.circular = false; + Config.fullScreenMap.coordsEnabled = false; + + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); + + Config.largeMap.heightPercent = -1; + Config.largeMap.marginTop = 10; + Config.largeMap.marginBottom = 40; + Config.largeMap.marginLeft = 40; + Config.largeMap.marginRight = 40; + Config.largeMap.playerArrowSize = 5; + Config.largeMap.markerSize = 5; + Config.largeMap.coordsEnabled = true; + + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); + + Config.smallMap.heightPercent = 30; + Config.smallMap.marginTop = 10; + Config.smallMap.marginBottom = -1; + Config.smallMap.marginLeft = -1; + Config.smallMap.marginRight = 10; + Config.smallMap.playerArrowSize = 4; + Config.smallMap.markerSize = 3; + Config.smallMap.coordsEnabled = true; + } + } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 08fd3b83..63ec6f4a 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -1,320 +1,320 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.Mw; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Config; -import mapwriter.util.Render; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -public class MapRenderer { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - // accessed by the MwGui to check whether the mouse cursor is near the - // player arrow on the rendered map - public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { - this.mw = mw; - this.mapMode = mapMode; - this.mapView = mapView; - } - - private void drawMap() { - - int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) Config.textureSize; - double zoomScale = (double) (1 << regionZoomLevel); - - // if the texture UV coordinates do not line up with the texture pixels then the texture - // will look blurry when it is drawn to the screen. - // to fix this we round the texture coordinates to the nearest pixel boundary. - // this is unnecessary when zoomed in as the texture will be upscaled and look blurry - // anyway, so it is disabled in this case. - // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture - // pixel boundaries when zoomed in. - - double u, v, w, h; - if ((!this.mapMode.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { - u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; - v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; - w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; - h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; - } else { - double tSizeInBlocks = tSize * zoomScale; - u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; - v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; - w = (this.mapView.getWidth() / tSizeInBlocks); - h = (this.mapView.getHeight() / tSizeInBlocks); - } - - GL11.glPushMatrix(); - - if (this.mapMode.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - if (this.mapMode.circular) { - Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); - } - - if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { - // draw the underground map - this.mw.undergroundMapTexture.requestView(this.mapView); - // underground map needs to have a black background - Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - this.mw.undergroundMapTexture.bind(); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } else { - // draw the surface map - MapViewRequest req = new MapViewRequest(this.mapView); - this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); - - // draw the background texture - if (Config.backgroundTextureMode > 0) { - double bu1 = 0.0; double bu2 = 1.0; - double bv1 = 0.0; double bv2 = 1.0; - if (Config.backgroundTextureMode == 2) { - // background moves with map if mode is 2 - double bSize = tSize / 256.0; - bu1 = u * bSize; bu2 = (u + w) * bSize; - bv1 = v * bSize; bv2 = (v + h) * bSize; - } - this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - bu1, bv1, bu2, bv2 - ); - } else { - // mode 0, no background texture - Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - } - - // only draw surface map if the request is loaded (view requests are - // loaded by the background thread) - if (this.mw.mapTexture.isLoaded(req)) { - this.mw.mapTexture.bind(); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } - } - - // draw ProfMobius chunk overlay - IMwDataProvider provider = this.drawOverlay(); - - // overlay onDraw event - if (provider != null) { - GL11.glPushMatrix(); - provider.onDraw(this.mapView, this.mapMode); - GL11.glPopMatrix(); - } - - if (this.mapMode.circular) { - Render.disableStencil(); - } - - GL11.glPopMatrix(); - } - - private void drawBorder() { - if (this.mapMode.circular) { - this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); - } else { - this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); - } - Render.setColour(0xffffffff); - Render.drawTexturedRect( - this.mapMode.x / 0.75, this.mapMode.y / 0.75, - this.mapMode.w / 0.75, this.mapMode.h / 0.75, - 0.0, 0.0, 1.0, 1.0 - ); - } - - private void drawPlayerArrow() { - GL11.glPushMatrix(); - double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); - Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); - this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); - - // the arrow only needs to be rotated if the map is NOT rotated - GL11.glTranslated(p.x, p.y, 0.0); - if (!this.mapMode.rotate) { - GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - double arrowSize = this.mapMode.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); - Render.drawTexturedRect( - -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - GL11.glPopMatrix(); - } - - private void drawIcons() { - GL11.glPushMatrix(); - - if (this.mapMode.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - // draw markers - this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); - - // draw player trail - if (this.mw.playerTrail.enabled) { - this.mw.playerTrail.draw(this.mapMode, this.mapView); - } - - // draw north arrow - if (this.mapMode.rotate) { - double y = this.mapMode.h / 2.0; - double arrowSize = this.mapMode.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); - Render.drawTexturedRect( - -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - } - - GL11.glPopMatrix(); - - // outside of the matrix pop as theplayer arrow - // needs to be drawn without rotation - this.drawPlayerArrow(); - } - - private void drawCoords() { - // draw coordinates - if (this.mapMode.coordsEnabled) { - GL11.glPushMatrix(); - GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (Config.coordsMode != 2) { - GL11.glScalef(0.5f, 0.5f, 1.0f); - } - int offset = 0; - if (Config.coordsMode > 0) { - Render.drawCentredString(0, 0, this.mapMode.textColour, - "%d, %d, %d", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt - ); - offset += 12; - } - if (Config.undergroundMode) { - Render.drawCentredString( - 0, offset, this.mapMode.textColour,"underground mode" - ); - } - GL11.glPopMatrix(); - } - } - - private IMwDataProvider drawOverlay() { - // draw overlays from registered providers - //for (IMwDataProvider provider : MwAPI.getDataProviders()) - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) { - ArrayList overlays = provider.getChunksOverlay( - this.mapView.getDimension(), - this.mapView.getX(), this.mapView.getZ(), - this.mapView.getMinX(), this.mapView.getMinZ(), - this.mapView.getMaxX(), this.mapView.getMaxZ() - ); - if (overlays != null) { - for (IMwChunkOverlay overlay : overlays) { - paintChunk(this.mapMode, this.mapView, overlay); - } - } - } - return provider; - } - - public void draw() { - - this.mapMode.setScreenRes(); - this.mapView.setMapWH(this.mapMode); - this.mapView.setTextureSize(Config.textureSize); - - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - - // translate to center of minimap - // z is -2000 so that it is drawn above the 3D world, but below GUI - // elements which are typically at -3000 - GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); - - // draw background, the map texture, and enabled overlays - this.drawMap(); - - if (this.mapMode.borderMode > 0) { - this.drawBorder(); - } - this.drawIcons(); - - this.drawCoords(); - - // some shader mods seem to need depth testing re-enabled - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); - } - - private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ - int chunkX = overlay.getCoordinates().x; - int chunkZ = overlay.getCoordinates().y; - float filling = overlay.getFilling(); - - Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); - Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); - - topCorner.x = Math.max(mapMode.x, topCorner.x); - topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); - topCorner.y = Math.max(mapMode.y, topCorner.y); - topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); - - botCorner.x = Math.max(mapMode.x, botCorner.x); - botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); - botCorner.y = Math.max(mapMode.y, botCorner.y); - botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); - - double sizeX = (botCorner.x - topCorner.x) * filling; - double sizeY = (botCorner.y - topCorner.y) * filling; - double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; - double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; - - if (overlay.hasBorder()) { - Render.setColour(overlay.getBorderColor()); - Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); - } - - Render.setColour(overlay.getColor()); - Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); - } -} - +package mapwriter.map; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.Mw; +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Config; +import mapwriter.util.Render; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +public class MapRenderer { + private Mw mw; + private MapMode mapMode; + private MapView mapView; + // accessed by the MwGui to check whether the mouse cursor is near the + // player arrow on the rendered map + public Point.Double playerArrowScreenPos = new Point.Double(0, 0); + + private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { + this.mw = mw; + this.mapMode = mapMode; + this.mapView = mapView; + } + + private void drawMap() { + + int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); + double tSize = (double) Config.textureSize; + double zoomScale = (double) (1 << regionZoomLevel); + + // if the texture UV coordinates do not line up with the texture pixels then the texture + // will look blurry when it is drawn to the screen. + // to fix this we round the texture coordinates to the nearest pixel boundary. + // this is unnecessary when zoomed in as the texture will be upscaled and look blurry + // anyway, so it is disabled in this case. + // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture + // pixel boundaries when zoomed in. + + double u, v, w, h; + if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; + v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; + w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; + h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; + } else { + double tSizeInBlocks = tSize * zoomScale; + u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; + v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; + w = (this.mapView.getWidth() / tSizeInBlocks); + h = (this.mapView.getHeight() / tSizeInBlocks); + } + + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + if (this.mapMode.config.circular) { + Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); + } + + if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { + // draw the underground map + this.mw.undergroundMapTexture.requestView(this.mapView); + // underground map needs to have a black background + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + this.mw.undergroundMapTexture.bind(); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } else { + // draw the surface map + MapViewRequest req = new MapViewRequest(this.mapView); + this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); + + // draw the background texture + if (Config.backgroundTextureMode > 0) { + double bu1 = 0.0; double bu2 = 1.0; + double bv1 = 0.0; double bv2 = 1.0; + if (Config.backgroundTextureMode == 2) { + // background moves with map if mode is 2 + double bSize = tSize / 256.0; + bu1 = u * bSize; bu2 = (u + w) * bSize; + bv1 = v * bSize; bv2 = (v + h) * bSize; + } + this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + bu1, bv1, bu2, bv2 + ); + } else { + // mode 0, no background texture + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + } + + // only draw surface map if the request is loaded (view requests are + // loaded by the background thread) + if (this.mw.mapTexture.isLoaded(req)) { + this.mw.mapTexture.bind(); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } + } + + // draw ProfMobius chunk overlay + IMwDataProvider provider = this.drawOverlay(); + + // overlay onDraw event + if (provider != null) { + GL11.glPushMatrix(); + provider.onDraw(this.mapView, this.mapMode); + GL11.glPopMatrix(); + } + + if (this.mapMode.config.circular) { + Render.disableStencil(); + } + + GL11.glPopMatrix(); + } + + private void drawBorder() { + if (this.mapMode.config.circular) { + this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); + } else { + this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); + } + Render.setColour(0xffffffff); + Render.drawTexturedRect( + this.mapMode.x / 0.75, this.mapMode.y / 0.75, + this.mapMode.w / 0.75, this.mapMode.h / 0.75, + 0.0, 0.0, 1.0, 1.0 + ); + } + + private void drawPlayerArrow() { + GL11.glPushMatrix(); + double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); + Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); + this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); + + // the arrow only needs to be rotated if the map is NOT rotated + GL11.glTranslated(p.x, p.y, 0.0); + if (!this.mapMode.config.rotate) { + GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); + Render.drawTexturedRect( + -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + GL11.glPopMatrix(); + } + + private void drawIcons() { + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + // draw markers + this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); + + // draw player trail + if (this.mw.playerTrail.enabled) { + this.mw.playerTrail.draw(this.mapMode, this.mapView); + } + + // draw north arrow + if (this.mapMode.config.rotate) { + double y = this.mapMode.h / 2.0; + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); + Render.drawTexturedRect( + -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + } + + GL11.glPopMatrix(); + + // outside of the matrix pop as theplayer arrow + // needs to be drawn without rotation + this.drawPlayerArrow(); + } + + private void drawCoords() { + // draw coordinates + if (this.mapMode.config.coordsEnabled) { + GL11.glPushMatrix(); + GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); + if (Config.coordsMode != Config.coordsModeStringArray[2]) { + GL11.glScalef(0.5f, 0.5f, 1.0f); + } + int offset = 0; + if (Config.coordsMode != Config.coordsModeStringArray[0]) { + Render.drawCentredString(0, 0, this.mapMode.textColour, + "%d, %d, %d", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt + ); + offset += 12; + } + if (Config.undergroundMode) { + Render.drawCentredString( + 0, offset, this.mapMode.textColour,"underground mode" + ); + } + GL11.glPopMatrix(); + } + } + + private IMwDataProvider drawOverlay() { + // draw overlays from registered providers + //for (IMwDataProvider provider : MwAPI.getDataProviders()) + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) { + ArrayList overlays = provider.getChunksOverlay( + this.mapView.getDimension(), + this.mapView.getX(), this.mapView.getZ(), + this.mapView.getMinX(), this.mapView.getMinZ(), + this.mapView.getMaxX(), this.mapView.getMaxZ() + ); + if (overlays != null) { + for (IMwChunkOverlay overlay : overlays) { + paintChunk(this.mapMode, this.mapView, overlay); + } + } + } + return provider; + } + + public void draw() { + + this.mapMode.setScreenRes(); + this.mapView.setMapWH(this.mapMode); + this.mapView.setTextureSize(Config.textureSize); + + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + + // translate to center of minimap + // z is -2000 so that it is drawn above the 3D world, but below GUI + // elements which are typically at -3000 + GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); + + // draw background, the map texture, and enabled overlays + this.drawMap(); + + if (this.mapMode.config.borderMode > 0) { + this.drawBorder(); + } + this.drawIcons(); + + this.drawCoords(); + + // some shader mods seem to need depth testing re-enabled + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + + private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ + int chunkX = overlay.getCoordinates().x; + int chunkZ = overlay.getCoordinates().y; + float filling = overlay.getFilling(); + + Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); + Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); + + topCorner.x = Math.max(mapMode.x, topCorner.x); + topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); + topCorner.y = Math.max(mapMode.y, topCorner.y); + topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); + + botCorner.x = Math.max(mapMode.x, botCorner.x); + botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); + botCorner.y = Math.max(mapMode.y, botCorner.y); + botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); + + double sizeX = (botCorner.x - topCorner.x) * filling; + double sizeY = (botCorner.y - topCorner.y) * filling; + double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; + double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; + + if (overlay.hasBorder()) { + Render.setColour(overlay.getBorderColor()); + Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); + } + + Render.setColour(overlay.getColor()); + Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); + } +} + diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index 3b78c42c..67bdb9de 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -57,8 +57,8 @@ public void draw(MapMode mapMode, MapView mapView, int borderColour) { this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); // draw a coloured rectangle centered on the calculated (x, y) - double mSize = mapMode.markerSize; - double halfMSize = mapMode.markerSize / 2.0; + double mSize = mapMode.config.markerSize; + double halfMSize = mapMode.config.markerSize / 2.0; Render.setColour(borderColour); Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); Render.setColour(this.colour); diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index 37e669ae..93feed2d 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -1,92 +1,85 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.map.mapmode.LargeMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.map.mapmode.SmallMapMode; -import mapwriter.util.Config; -import mapwriter.util.Reference; - -public class MiniMap { - private Mw mw; - - public static final String catSmallMap = "smallMap"; - public static final String catLargeMap = "largeMap"; - public static final String catUndergroundMap = "undergroundMap"; - - public MapMode smallMapMode; - public MapMode largeMapMode; - public MapMode guiMapMode; - - public MapView view; - - public MapRenderer smallMap; - public MapRenderer largeMap; - - private List mapList; - private MapRenderer currentMap = null; - - public MiniMap(Mw mw) { - this.mw = mw; - - // map view shared between large and small map modes - this.view = new MapView(mw); - this.view.setZoomLevel(Config.zoomLevel); - - // small map mode - this.smallMapMode = new SmallMapMode(); - this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); - - // large map mode - this.largeMapMode = new LargeMapMode(); - this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); - - this.mapList = new ArrayList(); - - // add small, large and underground map modes if they - // are enabled. - if (this.smallMapMode.enabled) { - this.mapList.add(this.smallMap); - } - if (this.largeMapMode.enabled) { - this.mapList.add(this.largeMap); - } - // add a null entry (hides the overlay when selected) - this.mapList.add(null); - - // sanitize overlayModeIndex loaded from config - this.nextOverlayMode(0); - this.currentMap = this.mapList.get(Config.modeIndex); - } - - public void close() { - this.mapList.clear(); - this.currentMap = null; - - this.smallMapMode.close(); - this.largeMapMode.close(); - } - - // toggle between small map, underground map and no map - public MapRenderer nextOverlayMode(int increment) { - int size = this.mapList.size(); - Config.modeIndex = (Config.modeIndex + size + increment) % size; - this.currentMap = this.mapList.get(Config.modeIndex); - return this.currentMap; - } - - public void toggleRotating() { - boolean rotate = this.smallMapMode.toggleRotating(); - this.largeMapMode.setRotating(rotate); - } - - // draw the map overlay, player arrow, and markers - public void drawCurrentMap() { - if (this.currentMap != null) { - this.currentMap.draw(); - } - } +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.map.mapmode.LargeMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.map.mapmode.SmallMapMode; +import mapwriter.util.Config; +import mapwriter.util.Reference; + +public class MiniMap { + private Mw mw; + + public MapMode smallMapMode; + public MapMode largeMapMode; + public MapMode guiMapMode; + + public MapView view; + + public MapRenderer smallMap; + public MapRenderer largeMap; + + private List mapList; + private MapRenderer currentMap = null; + + public MiniMap(Mw mw) { + this.mw = mw; + + // map view shared between large and small map modes + this.view = new MapView(mw); + this.view.setZoomLevel(Config.zoomLevel); + + // small map mode + this.smallMapMode = new SmallMapMode(); + this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); + + // large map mode + this.largeMapMode = new LargeMapMode(); + this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); + + this.mapList = new ArrayList(); + + // add small, large and underground map modes if they + // are enabled. + if (this.smallMapMode.config.enabled) { + this.mapList.add(this.smallMap); + } + if (this.largeMapMode.config.enabled) { + this.mapList.add(this.largeMap); + } + // add a null entry (hides the overlay when selected) + this.mapList.add(null); + + // sanitize overlayModeIndex loaded from config + this.nextOverlayMode(0); + this.currentMap = this.mapList.get(Config.modeIndex); + } + + public void close() { + this.mapList.clear(); + this.currentMap = null; + } + + // toggle between small map, underground map and no map + public MapRenderer nextOverlayMode(int increment) { + int size = this.mapList.size(); + Config.modeIndex = (Config.modeIndex + size + increment) % size; + this.currentMap = this.mapList.get(Config.modeIndex); + return this.currentMap; + } + + public void toggleRotating() { + boolean rotate = this.smallMapMode.toggleRotating(); + this.largeMapMode.setRotating(rotate); + } + + // draw the map overlay, player arrow, and markers + public void drawCurrentMap() { + if (this.currentMap != null) { + this.currentMap.draw(); + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java index 41843da5..1b2c4100 100644 --- a/src/main/java/mapwriter/map/Trail.java +++ b/src/main/java/mapwriter/map/Trail.java @@ -1,100 +1,100 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.LinkedList; - -import mapwriter.Mw; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Reference; -import mapwriter.util.Render; - -public class Trail { - - class TrailMarker { - - double x, y, z, heading; - int alphaPercent; - - static final int borderColour = 0xff000000; - static final int colour = 0xff00ffff; - - public TrailMarker(double x, double y, double z, double heading) { - this.set(x, y, z, heading); - } - - public void set(double x, double y, double z, double heading) { - this.x = x; - this.y = y; - this.z = z; - this.heading = heading; - this.alphaPercent = 100; - } - - public void draw(MapMode mapMode, MapView mapView) { - if (mapView.isBlockWithinView(this.x, this.z, mapMode.circular)) { - Point.Double p = mapMode.blockXZtoScreenXY(mapView, this.x, this.z); - - // draw a coloured arrow centered on the calculated (x, y) - Render.setColourWithAlphaPercent(borderColour, this.alphaPercent); - Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize); - Render.setColourWithAlphaPercent(colour, this.alphaPercent); - Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize - 1.0); - } - } - } - - private Mw mw; - public LinkedList trailMarkerList = new LinkedList(); - public int maxLength = 30; - public String name; - public boolean enabled; - public long lastMarkerTime = 0; - public long intervalMillis = 5000; - - public Trail(Mw mw, String name) { - this.mw = mw; - this.name = name; - this.enabled = ConfigurationHandler.configuration.getBoolean(this.name + "TrailEnabled", Reference.catOptions, false, ""); - this.maxLength = ConfigurationHandler.configuration.getInt(this.name + "TrailMaxLength", Reference.catOptions, this.maxLength, 1, 200, ""); - this.intervalMillis = (long) ConfigurationHandler.configuration.getInt(this.name + "TrailMarkerIntervalMillis", Reference.catOptions, (int) this.intervalMillis, 100, 360000, ""); - } - - public void close() { - //this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); - //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); - //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); - this.trailMarkerList.clear(); - } - - // for other types of trails will need to extend Trail and override this method - public void onTick() { - long time = System.currentTimeMillis(); - if ((time - this.lastMarkerTime) > this.intervalMillis) { - this.lastMarkerTime = time; - this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); - } - } - - public void addMarker(double x, double y, double z, double heading) { - this.trailMarkerList.add(new TrailMarker(x, y, z, heading)); - // remove elements from beginning of list until the list has at most - // maxTrailLength elements - while (this.trailMarkerList.size() > this.maxLength) { - this.trailMarkerList.poll(); - } - int i = this.maxLength - this.trailMarkerList.size(); - for (TrailMarker marker : this.trailMarkerList) { - marker.alphaPercent = (i * 100) / this.maxLength; - i++; - } - } - - public void draw(MapMode mapMode, MapView mapView) { - for (TrailMarker marker : this.trailMarkerList) { - marker.draw(mapMode, mapView); - } - } - - -} +package mapwriter.map; + +import java.awt.Point; +import java.util.LinkedList; + +import mapwriter.Mw; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Reference; +import mapwriter.util.Render; + +public class Trail { + + class TrailMarker { + + double x, y, z, heading; + int alphaPercent; + + static final int borderColour = 0xff000000; + static final int colour = 0xff00ffff; + + public TrailMarker(double x, double y, double z, double heading) { + this.set(x, y, z, heading); + } + + public void set(double x, double y, double z, double heading) { + this.x = x; + this.y = y; + this.z = z; + this.heading = heading; + this.alphaPercent = 100; + } + + public void draw(MapMode mapMode, MapView mapView) { + if (mapView.isBlockWithinView(this.x, this.z, mapMode.config.circular)) { + Point.Double p = mapMode.blockXZtoScreenXY(mapView, this.x, this.z); + + // draw a coloured arrow centered on the calculated (x, y) + Render.setColourWithAlphaPercent(borderColour, this.alphaPercent); + Render.drawArrow(p.x, p.y, this.heading, mapMode.config.trailMarkerSize); + Render.setColourWithAlphaPercent(colour, this.alphaPercent); + Render.drawArrow(p.x, p.y, this.heading, mapMode.config.trailMarkerSize - 1.0); + } + } + } + + private Mw mw; + public LinkedList trailMarkerList = new LinkedList(); + public int maxLength = 30; + public String name; + public boolean enabled; + public long lastMarkerTime = 0; + public long intervalMillis = 5000; + + public Trail(Mw mw, String name) { + this.mw = mw; + this.name = name; + this.enabled = ConfigurationHandler.configuration.getBoolean(this.name + "TrailEnabled", Reference.catOptions, false, ""); + this.maxLength = ConfigurationHandler.configuration.getInt(this.name + "TrailMaxLength", Reference.catOptions, this.maxLength, 1, 200, ""); + this.intervalMillis = (long) ConfigurationHandler.configuration.getInt(this.name + "TrailMarkerIntervalMillis", Reference.catOptions, (int) this.intervalMillis, 100, 360000, ""); + } + + public void close() { + //this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); + //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); + //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); + this.trailMarkerList.clear(); + } + + // for other types of trails will need to extend Trail and override this method + public void onTick() { + long time = System.currentTimeMillis(); + if ((time - this.lastMarkerTime) > this.intervalMillis) { + this.lastMarkerTime = time; + this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); + } + } + + public void addMarker(double x, double y, double z, double heading) { + this.trailMarkerList.add(new TrailMarker(x, y, z, heading)); + // remove elements from beginning of list until the list has at most + // maxTrailLength elements + while (this.trailMarkerList.size() > this.maxLength) { + this.trailMarkerList.poll(); + } + int i = this.maxLength - this.trailMarkerList.size(); + for (TrailMarker marker : this.trailMarkerList) { + marker.alphaPercent = (i * 100) / this.maxLength; + i++; + } + } + + public void draw(MapMode mapMode, MapView mapView) { + for (TrailMarker marker : this.trailMarkerList) { + marker.draw(mapMode, mapView); + } + } + + +} diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java index 6e717f41..af42b224 100644 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -1,25 +1,11 @@ -package mapwriter.map.mapmode; - - -public class FullScreenMapMode extends MapMode { - public FullScreenMapMode() { - super("fullScreenMap"); - - this.heightPercent = -1; - this.marginTop = 0; - this.marginBottom = 0; - this.marginLeft = 0; - this.marginRight = 0; - - this.borderMode = 0; - this.playerArrowSize = 5; - this.markerSize = 5; - this.alphaPercent = 100; - - this.rotate = false; - this.circular = false; - this.coordsEnabled = false; - - this.loadConfig(); - } -} +package mapwriter.map.mapmode; + +import mapwriter.util.Config; +import mapwriter.util.Reference; + + +public class FullScreenMapMode extends MapMode { + public FullScreenMapMode() { + super(Config.fullScreenMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java index 15a12ccf..03a83b83 100644 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -1,21 +1,11 @@ -package mapwriter.map.mapmode; - - -public class LargeMapMode extends MapMode { - public LargeMapMode() { - super("largeMap"); - - this.heightPercent = -1; - this.marginTop = 10; - this.marginBottom = 40; - this.marginLeft = 40; - this.marginRight = 40; - - this.playerArrowSize = 5; - this.markerSize = 5; - - this.coordsEnabled = true; - - this.loadConfig(); - } -} +package mapwriter.map.mapmode; + +import mapwriter.util.Config; +import mapwriter.util.Reference; + + +public class LargeMapMode extends MapMode { + public LargeMapMode() { + super(Config.largeMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 52ccb94f..37a943b1 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -1,252 +1,208 @@ -package mapwriter.map.mapmode; - -import java.awt.Point; - -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.MapView; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; - -public class MapMode { - public final String configCategory; - - private int sw = 320; - private int sh = 240; - private double screenScalingFactor = 1.0; - - // calculated before every frame drawn by updateMapDimensions - public int xTranslation = 0; - public int yTranslation = 0; - public int x = -25; - public int y = -25; - public int w = 50; - public int h = 50; - public int wPixels = 50; - public int hPixels = 50; - - // config settings - public boolean enabled = true; - public boolean rotate = true; - public boolean circular = true; - public boolean coordsEnabled = false; - public int borderMode = 1; - public int playerArrowSize = 5; - public int markerSize = 5; - public int trailMarkerSize = 3; - public int alphaPercent = 100; - - public int marginTop = 0; - public int marginBottom = 0; - public int marginLeft = 0; - public int marginRight = 0; - public int heightPercent = -1; - - public int textX = 0; - public int textY = 0; - public int textColour = 0xffffffff; - - public MapMode(String configCategory) { - this.configCategory = configCategory; - } - - public void loadConfig() { - // get options from config file - this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, ""); - this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, ""); - this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, ""); - this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, ""); - - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, ""); - this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, ""); - this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, ""); - this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, ""); - this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, ""); - - this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, ""); - this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, ""); - this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, ""); - this.borderMode = ConfigurationHandler.configuration.getInt("borderMode", this.configCategory, this.borderMode, 0, 1, ""); - - this.trailMarkerSize = Math.max(1, this.markerSize - 1); - } - - public void saveConfig() { - //this.config.setBoolean(this.configCategory, "enabled", this.enabled); - //this.config.setInt(this.configCategory, "heightPercent", this.heightPercent); - //this.config.setInt(this.configCategory, "marginTop", this.marginTop); - //this.config.setInt(this.configCategory, "marginBottom", this.marginBottom); - //this.config.setInt(this.configCategory, "marginLeft", this.marginLeft); - //this.config.setInt(this.configCategory, "marginRight", this.marginRight); - //this.config.setBoolean(this.configCategory, "rotate", this.rotate); - //this.config.setBoolean(this.configCategory, "circular", this.circular); - } - - public void close() { - this.saveConfig(); - } - - public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { - if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { - this.sw = sw; - this.sh = sh; - this.screenScalingFactor = scaling; - this.update(); - } - } - - public void setScreenRes() { - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); - } - - public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { - this.marginTop = marginTop; - this.marginBottom = marginBottom; - this.marginLeft = marginLeft; - this.marginRight = marginRight; - this.update(); - } - - public void setHeightPercent(int heightPercent) { - this.heightPercent = heightPercent; - this.update(); - } - - public void toggleHeightPercent() { - int i = (this.heightPercent / 5) + 1; - if (i > 12) { - i = 1; - } - this.setHeightPercent(i * 5); - } - - private void update() { - int size = (this.sh * this.heightPercent) / 100; - int x, y; - - // calculate map x position and width - if ((this.marginLeft >= 0) && (this.marginRight >= 0)) { - x = this.marginLeft; - this.w = this.sw - this.marginLeft - this.marginRight; - } else if (this.marginLeft >= 0) { - x = this.marginLeft; - this.w = size; - } else if (this.marginRight >= 0) { - x = this.sw - size - this.marginRight; - this.w = size; - } else { - x = (this.sw - size) / 2; - this.w = size; - } - - // calculate map y position and height - if ((this.marginTop >= 0) && (this.marginBottom >= 0)) { - y = this.marginTop; - this.h = this.sh - this.marginTop - this.marginBottom; - } else if (this.marginTop >= 0) { - y = this.marginTop; - this.h = size; - } else if (this.marginBottom >= 0) { - y = this.sh - size - this.marginBottom; - this.h = size; - } else { - y = (this.sh - size) / 2; - this.h = size; - } - - // make sure width and height are multiples of 2 - this.w &= -2; - this.h &= -2; - - this.xTranslation = x + (this.w >> 1); - this.yTranslation = y + (this.h >> 1); - - if (this.circular) { - this.w = this.h; - } - - this.x = -(this.w >> 1); - this.y = -(this.h >> 1); - - this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); - this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); - - // calculate coords display location - this.textX = 0; - this.textY = (this.h >> 1) + 4; - - //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); - //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", - // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); - } - - public void setRotating(boolean enabled) { - this.rotate = enabled; - this.circular = enabled; - this.update(); - } - - public boolean toggleRotating() { - this.setRotating(!this.rotate); - return this.rotate; - } - - public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { - double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); - double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); - int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); - int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); - return new Point(bx, bz); - } - - public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { - double xNorm = (bX - mapView.getX()) / mapView.getWidth(); - double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); - return new Point.Double(this.w * xNorm, this.h * zNorm); - } - - public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { - double xRel = (bX - mapView.getX()) / mapView.getWidth(); - double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); - double limit = 0.49; - - if (!this.circular) { - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - if (zRel < -limit) { - xRel = -limit * xRel / zRel; - zRel = -limit; - } - if (zRel > limit) { - xRel = limit * xRel / zRel; - zRel = limit; - } - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - } else { - double dSq = (xRel * xRel) + (zRel * zRel); - if (dSq > (limit * limit)) { - double a = Math.atan2(zRel, xRel); - xRel = limit * Math.cos(a); - zRel = limit * Math.sin(a); - } - } - - // multiply by the overlay size and add the overlay position to - // get the position within the overlay in screen coordinates - return new Point.Double(this.w * xRel, this.h * zRel); - } -} +package mapwriter.map.mapmode; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.MapView; +import mapwriter.util.MapModeConfig; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class MapMode { + private int sw = 320; + private int sh = 240; + private double screenScalingFactor = 1.0; + + // calculated before every frame drawn by updateMapDimensions + public int xTranslation = 0; + public int yTranslation = 0; + public int x = -25; + public int y = -25; + public int w = 50; + public int h = 50; + public int wPixels = 50; + public int hPixels = 50; + + // config settings + + public int textX = 0; + public int textY = 0; + public int textColour = 0xffffffff; + + public MapModeConfig config; + + public MapMode(MapModeConfig config) { + this.config = config; + } + + public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { + if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { + this.sw = sw; + this.sh = sh; + this.screenScalingFactor = scaling; + this.update(); + } + } + + public void setScreenRes() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); + } + + public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { + this.config.marginTop = marginTop; + this.config.marginBottom = marginBottom; + this.config.marginLeft = marginLeft; + this.config.marginRight = marginRight; + this.update(); + } + + public void setHeightPercent(int heightPercent) { + this.config.heightPercent = heightPercent; + this.update(); + } + + public void toggleHeightPercent() { + int i = (this.config.heightPercent / 5) + 1; + if (i > 12) { + i = 1; + } + this.setHeightPercent(i * 5); + } + + private void update() { + int size = (this.sh * this.config.heightPercent) / 100; + int x, y; + + // calculate map x position and width + if ((this.config.marginLeft >= 0) && (this.config.marginRight >= 0)) { + x = this.config.marginLeft; + this.w = this.sw - this.config.marginLeft - this.config.marginRight; + } else if (this.config.marginLeft >= 0) { + x = this.config.marginLeft; + this.w = size; + } else if (this.config.marginRight >= 0) { + x = this.sw - size - this.config.marginRight; + this.w = size; + } else { + x = (this.sw - size) / 2; + this.w = size; + } + + // calculate map y position and height + if ((this.config.marginTop >= 0) && (this.config.marginBottom >= 0)) { + y = this.config.marginTop; + this.h = this.sh - this.config.marginTop - this.config.marginBottom; + } else if (this.config.marginTop >= 0) { + y = this.config.marginTop; + this.h = size; + } else if (this.config.marginBottom >= 0) { + y = this.sh - size - this.config.marginBottom; + this.h = size; + } else { + y = (this.sh - size) / 2; + this.h = size; + } + + // make sure width and height are multiples of 2 + this.w &= -2; + this.h &= -2; + + this.xTranslation = x + (this.w >> 1); + this.yTranslation = y + (this.h >> 1); + + if (this.config.circular) { + this.w = this.h; + } + + this.x = -(this.w >> 1); + this.y = -(this.h >> 1); + + this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); + this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); + + // calculate coords display location + this.textX = 0; + this.textY = (this.h >> 1) + 4; + + //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); + //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", + // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); + } + + public void setRotating(boolean enabled) { + this.config.rotate = enabled; + this.config.circular = enabled; + this.update(); + } + + public boolean toggleRotating() { + this.setRotating(!this.config.rotate); + return this.config.rotate; + } + + public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { + double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); + double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); + int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); + int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); + return new Point(bx, bz); + } + + public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { + double xNorm = (bX - mapView.getX()) / mapView.getWidth(); + double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); + return new Point.Double(this.w * xNorm, this.h * zNorm); + } + + public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { + double xRel = (bX - mapView.getX()) / mapView.getWidth(); + double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); + double limit = 0.49; + + if (!this.config.circular) { + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + if (zRel < -limit) { + xRel = -limit * xRel / zRel; + zRel = -limit; + } + if (zRel > limit) { + xRel = limit * xRel / zRel; + zRel = limit; + } + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + } else { + double dSq = (xRel * xRel) + (zRel * zRel); + if (dSq > (limit * limit)) { + double a = Math.atan2(zRel, xRel); + xRel = limit * Math.cos(a); + zRel = limit * Math.sin(a); + } + } + + // multiply by the overlay size and add the overlay position to + // get the position within the overlay in screen coordinates + return new Point.Double(this.w * xRel, this.h * zRel); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java index 7daa1f9a..7d627434 100644 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -1,21 +1,11 @@ -package mapwriter.map.mapmode; - - -public class SmallMapMode extends MapMode { - public SmallMapMode() { - super("smallMap"); - - this.heightPercent = 30; - this.marginTop = 10; - this.marginBottom = -1; - this.marginLeft = -1; - this.marginRight = 10; - - this.playerArrowSize = 4; - this.markerSize = 3; - - this.coordsEnabled = true; - - this.loadConfig(); - } -} +package mapwriter.map.mapmode; + +import mapwriter.util.Config; +import mapwriter.util.Reference; + + +public class SmallMapMode extends MapMode { + public SmallMapMode() { + super(Config.smallMap); + } +} diff --git a/src/main/java/mapwriter/util/Config.java b/src/main/java/mapwriter/util/Config.java index e55674ab..5b4dcae0 100644 --- a/src/main/java/mapwriter/util/Config.java +++ b/src/main/java/mapwriter/util/Config.java @@ -1,9 +1,36 @@ package mapwriter.util; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; + public class Config { + public static final String[] miniMapPositionStringArray = { + "unchanged", + "top right", + "top left", + "bottom right", + "bottom left" + }; + public static final String[] coordsModeStringArray = { + "disabled", + "small", + "large" + }; + public static final String[] backgroundModeStringArray = { + "none", + "static", + "panning" + }; + // configuration options public static boolean linearTextureScalingEnabled = true; - public static int coordsMode = 0; + public static String coordsMode = coordsModeStringArray[0]; public static boolean undergroundMode = false; public static boolean teleportEnabled = true; public static String teleportCommand = "tp"; @@ -22,9 +49,12 @@ public class Config { public static boolean regionFileOutputEnabledSP = true; public static boolean regionFileOutputEnabledMP = true; public static int backgroundTextureMode = 0; - //public static boolean lightingEnabled = false; //World configuration Options public static int modeIndex = 0; public static int zoomLevel = 0; + + public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); + public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); + public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); } diff --git a/src/main/java/mapwriter/util/MapModeConfig.java b/src/main/java/mapwriter/util/MapModeConfig.java new file mode 100644 index 00000000..afa1bf95 --- /dev/null +++ b/src/main/java/mapwriter/util/MapModeConfig.java @@ -0,0 +1,64 @@ +package mapwriter.util; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class MapModeConfig { + + public final String configCategory; + + public boolean enabled = true; + public boolean rotate = true; + public boolean circular = true; + public boolean coordsEnabled = false; + public int borderMode = 1; + public int playerArrowSize = 5; + public int markerSize = 5; + public int trailMarkerSize = 3; + public int alphaPercent = 100; + + public int marginTop = 0; + public int marginBottom = 0; + public int marginLeft = 0; + public int marginRight = 0; + public int heightPercent = -1; + + public MapModeConfig(String configCategory) { + this.configCategory = configCategory; + } + + public void loadConfig() { + // get options from config file + this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, ""); + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, ""); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, ""); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, ""); + + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, ""); + this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, ""); + this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, ""); + this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, ""); + this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, ""); + + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, ""); + this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, ""); + this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, ""); + this.borderMode = ConfigurationHandler.configuration.getInt("borderMode", this.configCategory, this.borderMode, 0, 1, ""); + + this.trailMarkerSize = Math.max(1, this.markerSize - 1); + } + + public IConfigElement categoryElement(String name, String tooltip_key) + { + ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); + } +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index b7912020..74b10b27 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,19 +1,22 @@ -package mapwriter.util; - -import java.util.regex.Pattern; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public final static String catOptions = "options"; - - public final static String PlayerTrailName = "player"; - - public final static Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); -} +package mapwriter.util; + +import java.util.regex.Pattern; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public static final String catOptions = "options"; + public static final String catLargeMapConfig = "largemap"; + public static final String catSmallMapConfig = "smallmap"; + public static final String catFullMapConfig = "fullscreenmap"; + + public static final String PlayerTrailName = "player"; + + public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); +} From 2d036969728d4c0ab77d78592205455dd8209e32 Mon Sep 17 00:00:00 2001 From: blt Date: Tue, 21 Apr 2015 13:58:00 +0200 Subject: [PATCH 030/109] -Refactoring -More changes to config -made the mod client only --- src/main/java/mapwriter/ChunkManager.java | 7 +- src/main/java/mapwriter/Mw.java | 1115 +++++++------- .../mapwriter/{util => config}/Config.java | 121 +- .../{util => config}/MapModeConfig.java | 129 +- .../java/mapwriter/config/WorldConfig.java | 71 + .../java/mapwriter/forge/ClientProxy.java | 3 +- .../java/mapwriter/forge/EventHandler.java | 2 +- src/main/java/mapwriter/forge/MwForge.java | 19 +- .../java/mapwriter/forge/MwKeyHandler.java | 4 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 326 ++--- src/main/java/mapwriter/gui/MwGui.java | 1293 +++++++++-------- .../mapwriter/gui/MwGuiDimensionDialog.java | 3 +- .../mapwriter/gui/MwGuiTeleportDialog.java | 2 +- .../handler/ConfigurationHandler.java | 244 ++-- src/main/java/mapwriter/map/MapRenderer.java | 645 ++++---- src/main/java/mapwriter/map/MapView.java | 6 +- src/main/java/mapwriter/map/MiniMap.java | 174 +-- .../map/mapmode/FullScreenMapMode.java | 22 +- .../mapwriter/map/mapmode/LargeMapMode.java | 22 +- .../java/mapwriter/map/mapmode/MapMode.java | 416 +++--- .../mapwriter/map/mapmode/SmallMapMode.java | 22 +- src/main/java/mapwriter/util/Reference.java | 52 +- src/main/java/mapwriter/util/Utils.java | 38 + .../assets/mapwriter/lang/en_US.lang | 75 + 24 files changed, 2466 insertions(+), 2345 deletions(-) rename src/main/java/mapwriter/{util => config}/Config.java (87%) rename src/main/java/mapwriter/{util => config}/MapModeConfig.java (75%) create mode 100644 src/main/java/mapwriter/config/WorldConfig.java diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index d369f192..4c7408d2 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -4,11 +4,12 @@ import java.util.HashMap; import java.util.Map; +import mapwriter.config.Config; import mapwriter.region.MwChunk; import mapwriter.tasks.SaveChunkTask; import mapwriter.tasks.UpdateSurfaceChunksTask; -import mapwriter.util.Config; import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; @@ -141,8 +142,8 @@ public void forceChunks(MwChunk[] chunkArray){ } private void addSaveChunkTask(Chunk chunk) { - if ((this.mw.multiplayer && Config.regionFileOutputEnabledMP) || - (!this.mw.multiplayer && Config.regionFileOutputEnabledSP)) { + if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || + (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { if (!chunk.isEmpty()) { this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); } diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index bb255acd..e1c1bcd9 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -1,597 +1,518 @@ -package mapwriter; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.forge.MwForge; -import mapwriter.forge.MwKeyHandler; -import mapwriter.gui.MwGui; -import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.MapTexture; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.map.MiniMap; -import mapwriter.map.Trail; -import mapwriter.map.UndergroundTexture; -import mapwriter.overlay.OverlaySlime; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; -import mapwriter.tasks.CloseRegionManagerTask; -import mapwriter.util.Config; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Render; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.config.Configuration; - -public class Mw { - public Minecraft mc = null; - - // configuration files (global and world specific) - public static Configuration worldConfig = null; - - // server information - public String worldName = "default"; - private String serverName = "default"; - private int serverPort = 0; - - // directories - private final File configDir; - private final File saveDir; - public File worldDir = null; - public File imageDir = null; - - // flags and counters - public boolean ready = false; - public boolean multiplayer = false; - public int tickCounter = 0; - - // list of available dimensions - public List dimensionList = new ArrayList(); - - // player position and heading - public double playerX = 0.0; - public double playerZ = 0.0; - public double playerY = 0.0; - public int playerXInt = 0; - public int playerYInt = 0; - public int playerZInt = 0; - public double playerHeading = 0.0; - public int playerDimension = 0; - public double mapRotationDegrees = 0.0; - - // constants - public final static String catWorld = "world"; - public final static String catMarkers = "markers"; - public final static String worldDirConfigName = "mapwriter.cfg"; - public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - // instances of components - public MapTexture mapTexture = null; - public UndergroundTexture undergroundMapTexture = null; - public BackgroundExecutor executor = null; - public MiniMap miniMap = null; - public MarkerManager markerManager = null; - public BlockColours blockColours = null; - public RegionManager regionManager = null; - public ChunkManager chunkManager = null; - public Trail playerTrail = null; - - public static Mw instance; - - public Mw() { - // client only initialization - this.mc = Minecraft.getMinecraft(); - - // create base save directory - this.saveDir = new File(this.mc.mcDataDir, "saves"); - this.configDir = new File(this.mc.mcDataDir, "config"); - - this.ready = false; - - RegionManager.logger = MwForge.logger; - - instance = this; - - ConfigurationHandler.loadConfig(); - } - - public String getWorldName() { - String worldName; - if (this.multiplayer) { - if (Config.portNumberInWorldNameEnabled) { - worldName = String.format("%s_%d", this.serverName, this.serverPort); - } else { - worldName = String.format("%s", this.serverName); - } - - } else { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = this.mc.getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = Utils.mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - public void loadWorldConfig() { - // load world specific config file - File worldConfigFile = new File(this.worldDir, worldDirConfigName); - this.worldConfig = new Configuration(worldConfigFile); - this.worldConfig.load(); - - this.dimensionList.clear(); - this.worldConfig.get(catWorld, "dimensionList", Utils.integerListToIntArray(this.dimensionList)); - this.addDimension(0); - this.cleanDimensionList(); - } - - public void saveWorldConfig() { - //this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); - this.worldConfig.save(); - } - - public void setTextureSize() { - if (Config.configTextureSize != Config.textureSize) { - int maxTextureSize = Render.getMaxTextureSize(); - int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { - textureSize *= 2; - } - textureSize /= 2; - - Logging.log("GL reported max texture size = %d", maxTextureSize); - Logging.log("texture size from config = %d", Config.configTextureSize); - Logging.log("setting map texture size to = %d", textureSize); - - Config.textureSize = textureSize; - if (this.ready) { - // if we are already up and running need to close and reinitialize the map texture and - // region manager. - this.reloadMapTexture(); - } - } - } - - // update the saved player position and orientation - // called every tick - public void updatePlayer() { - // get player pos - this.playerX = (double) this.mc.thePlayer.posX; - this.playerY = (double) this.mc.thePlayer.posY; - this.playerZ = (double) this.mc.thePlayer.posZ; - this.playerXInt = (int) Math.floor(this.playerX); - this.playerYInt = (int) Math.floor(this.playerY); - this.playerZInt = (int) Math.floor(this.playerZ); - - // rotationYaw of 0 points due north, we want it to point due east instead - // so add pi/2 radians (90 degrees) - this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); - this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; - - // set by onWorldLoad - this.playerDimension = this.mc.theWorld.provider.getDimensionId(); - if (this.miniMap.view.getDimension() != this.playerDimension) - { - this.addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); - } - } - - public void addDimension(int dimension) { - int i = this.dimensionList.indexOf(dimension); - if (i < 0) { - this.dimensionList.add(dimension); - } - } - - public void cleanDimensionList() { - List dimensionListCopy = new ArrayList(this.dimensionList); - this.dimensionList.clear(); - for (int dimension : dimensionListCopy) { - this.addDimension(dimension); - } - } - - public void toggleMarkerMode() { - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - } - - // cheap and lazy way to teleport... - public void teleportTo(int x, int y, int z) { - if (Config.teleportEnabled) { - this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void warpTo(String name) { - if (Config.teleportEnabled) { - //MwUtil.printBoth(String.format("warping to %s", name)); - this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!Config.teleportCommand.equals("warp")) { - double scale = mapView.getDimensionScaling(this.playerDimension); - this.teleportTo((int) (x / scale), y, (int) (z / scale)); - } else { - Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); - } - } - - public void teleportToMarker(Marker marker) { - if (Config.teleportCommand.equals("warp")) { - this.warpTo(marker.name); - } else if (marker.dimension == this.playerDimension) { - this.teleportTo(marker.x, marker.y, marker.z); - } else { - Utils.printBoth("cannot teleport to marker in different dimension"); - } - } - - public void loadBlockColourOverrides(BlockColours bc) { - File f = new File(this.configDir, blockColourOverridesFileName); - if (f.isFile()) { - Logging.logInfo("loading block colour overrides file %s", f); - bc.loadFromFile(f); - } else { - Logging.logInfo("recreating block colour overrides file %s", f); - BlockColours.writeOverridesFile(f); - if (f.isFile()) { - bc.loadFromFile(f); - } else { - Logging.logError("could not load block colour overrides from file %s", f); - } - } - } - - public void saveBlockColours(BlockColours bc) { - File f = new File(this.configDir, blockColourSaveFileName); - Logging.logInfo("saving block colours to '%s'", f); - bc.saveToFile(f); - } - - public void reloadBlockColours() { - BlockColours bc = new BlockColours(); - File f = new File(this.configDir, blockColourSaveFileName); - if (Config.useSavedBlockColours && f.isFile()) { - // load block colours from file - Logging.logInfo("loading block colours from %s", f); - bc.loadFromFile(f); - this.loadBlockColourOverrides(bc); - } else { - // generate block colours from current texture pack - Logging.logInfo("generating block colours"); - // block type overrides need to be loaded before the block colours are generated - this.loadBlockColourOverrides(bc); - BlockColourGen.genBlockColours(bc); - // load overrides again to override block and biome colours - this.loadBlockColourOverrides(bc); - this.saveBlockColours(bc); - } - this.blockColours = bc; - } - - public void reloadMapTexture() { - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.executor.close(); - MapTexture oldMapTexture = this.mapTexture; - MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); - this.mapTexture = newMapTexture; - if (oldMapTexture != null) { - oldMapTexture.close(); - } - this.executor = new BackgroundExecutor(); - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); - - UndergroundTexture oldTexture = this.undergroundMapTexture; - UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); - this.undergroundMapTexture = newTexture; - if (oldTexture != null) { - this.undergroundMapTexture.close(); - } - } - - public void toggleUndergroundMode() { - Config.undergroundMode = !Config.undergroundMode; - this.miniMap.view.setUndergroundMode(Config.undergroundMode); - } - - public void setServerDetails(String hostname, int port) { - this.serverName = hostname; - this.serverPort = port; - } - - //////////////////////////////// - // Initialization and Cleanup - //////////////////////////////// - - public void load() { - - if (this.ready) { - return; - } - - if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { - Logging.log("Mw.load: world or player is null, cannot load yet"); - return; - } - - Logging.log("Mw.load: loading..."); - - IntegratedServer server = this.mc.getIntegratedServer(); - this.multiplayer = (server == null); - - this.worldName = this.getWorldName(); - - // get world and image directories - File saveDir = this.saveDir; - if (Config.saveDirOverride.length() > 0) { - File d = new File(Config.saveDirOverride); - if (d.isDirectory()) { - saveDir = d; - } else { - Logging.log("error: no such directory %s", Config.saveDirOverride); - } - } - - if (this.multiplayer) { - this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), this.worldName); - } else { - this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), this.worldName); - } - - this.loadWorldConfig(); - - // create directories - this.imageDir = new File(this.worldDir, "images"); - if (!this.imageDir.exists()) { - this.imageDir.mkdirs(); - } - if (!this.imageDir.isDirectory()) { - Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); - } - - this.tickCounter = 0; - - //this.multiplayer = !this.mc.isIntegratedServerRunning(); - - // marker manager only depends on the config being loaded - this.markerManager = new MarkerManager(); - this.markerManager.load(this.worldConfig, catMarkers); - - this.playerTrail = new Trail(this, Reference.PlayerTrailName); - - // executor does not depend on anything - this.executor = new BackgroundExecutor(); - - // mapTexture depends on config being loaded - this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScalingEnabled); - this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScalingEnabled); - this.reloadBlockColours(); - // region manager depends on config, mapTexture, and block colours - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.minZoom, Config.maxZoom); - // overlay manager depends on mapTexture - this.miniMap = new MiniMap(this); - this.miniMap.view.setDimension(this.mc.thePlayer.dimension); - - this.chunkManager = new ChunkManager(this); - - this.ready = true; - - //if (!zoomLevelsExist) { - //printBoth("recreating zoom levels"); - //this.regionManager.recreateAllZoomLevels(); - //} - } - - public void close() { - - Logging.log("Mw.close: closing..."); - - if (this.ready) { - this.ready = false; - - this.chunkManager.close(); - this.chunkManager = null; - - // close all loaded regions, saving modified images. - // this will create extra tasks that need to be completed. - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.regionManager = null; - - Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); - if (this.executor.close()) { - Logging.log("error: timeout waiting for tasks to finish"); - } - Logging.log("done"); - - this.playerTrail.close(); - - this.markerManager.save(this.worldConfig, catMarkers); - this.markerManager.clear(); - - // close overlay - this.miniMap.close(); - this.miniMap = null; - - this.undergroundMapTexture.close(); - this.mapTexture.close(); - - this.saveWorldConfig(); - //this.saveConfig(); - - this.tickCounter = 0; - - OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in - } - } - - //////////////////////////////// - // Event handlers - //////////////////////////////// - - public void onTick() { - this.load(); - if (this.ready && (this.mc.thePlayer != null)) { - - this.updatePlayer(); - - if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { - this.undergroundMapTexture.update(); - } - - if (!(this.mc.currentScreen instanceof MwGui)) { - // if in game (no gui screen) center the minimap on the player and render it. - this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); - this.miniMap.drawCurrentMap(); - } - - // process background tasks - int maxTasks = 50; - while (!this.executor.processTaskQueue() && (maxTasks > 0)) { - maxTasks--; - } - - this.chunkManager.onTick(); - - // update GL texture of mapTexture if updated - this.mapTexture.processTextureUpdates(); - - // let the renderEngine know we have changed the bound texture. - //this.mc.renderEngine.resetBoundTexture(); - - //if (this.tickCounter % 100 == 0) { - // MwUtil.log("tick %d", this.tickCounter); - //} - this.playerTrail.onTick(); - - this.tickCounter++; - } - } - - // add chunk to the set of loaded chunks - public void onChunkLoad(Chunk chunk) { - this.load(); - if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - if (this.ready) { - this.chunkManager.addChunk(chunk); - } else { - Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); - } - } - } - - // remove chunk from the set of loaded chunks. - // convert to mwchunk and write chunk to region file if in multiplayer. - public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - this.chunkManager.removeChunk(chunk); - } - } - - // from onTick when mc.currentScreen is an instance of GuiGameOver - // it's the only option to detect death client side - public void onPlayerDeath(EntityPlayerMP player) { - if (this.ready && (Config.maxDeathMarkers > 0)) { - this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; - for (int i = 0; i < deleteCount; i++) { - // delete the first marker found in the group "playerDeaths". - // as new markers are only ever appended to the marker list this will delete the - // earliest death marker added. - this.markerManager.delMarker(null, "playerDeaths"); - } - - this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); - this.markerManager.setVisibleGroupName("playerDeaths"); - this.markerManager.update(); - } - } - - public void onKeyDown(KeyBinding kb) { - // make sure not in GUI element (e.g. chat box) - if ((this.mc.currentScreen == null) && (this.ready)) { - //Mw.log("client tick: %s key pressed", kb.keyDescription); - - if (kb == MwKeyHandler.keyMapMode) { - // map mode toggle - this.miniMap.nextOverlayMode(1); - - } else if (kb == MwKeyHandler.keyMapGui) { - // open map gui - this.mc.displayGuiScreen(new MwGui(this)); - - } else if (kb == MwKeyHandler.keyNewMarker) { - // open new marker dialog - String group = this.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - - } else if (kb == MwKeyHandler.keyNextGroup) { - // toggle marker mode - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - - } else if (kb == MwKeyHandler.keyTeleport) { - // set or remove marker - Marker marker = this.markerManager.getNearestMarkerInDirection( - this.playerXInt, - this.playerZInt, - this.playerHeading); - if (marker != null) { - this.teleportToMarker(marker); - } - } else if (kb == MwKeyHandler.keyZoomIn) { - // zoom in - this.miniMap.view.adjustZoomLevel(-1); - } else if (kb == MwKeyHandler.keyZoomOut) { - // zoom out - this.miniMap.view.adjustZoomLevel(1); - } else if (kb == MwKeyHandler.keyUndergroundMode) { - this.toggleUndergroundMode(); - } - } - } -} +package mapwriter; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwForge; +import mapwriter.forge.MwKeyHandler; +import mapwriter.gui.MwGui; +import mapwriter.gui.MwGuiMarkerDialog; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.MapTexture; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.map.MiniMap; +import mapwriter.map.Trail; +import mapwriter.map.UndergroundTexture; +import mapwriter.overlay.OverlaySlime; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; +import mapwriter.tasks.CloseRegionManagerTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Render; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.config.Configuration; + +public class Mw { + public Minecraft mc = null; + + // directories + private final File configDir; + private final File saveDir; + public File worldDir = null; + public File imageDir = null; + + // flags and counters + public boolean ready = false; + //public boolean multiplayer = false; + public int tickCounter = 0; + + // player position and heading + public double playerX = 0.0; + public double playerZ = 0.0; + public double playerY = 0.0; + public int playerXInt = 0; + public int playerYInt = 0; + public int playerZInt = 0; + public double playerHeading = 0.0; + public int playerDimension = 0; + public double mapRotationDegrees = 0.0; + + // instances of components + public MapTexture mapTexture = null; + public UndergroundTexture undergroundMapTexture = null; + public BackgroundExecutor executor = null; + public MiniMap miniMap = null; + public MarkerManager markerManager = null; + public BlockColours blockColours = null; + public RegionManager regionManager = null; + public ChunkManager chunkManager = null; + public Trail playerTrail = null; + + private static Mw instance; + + public static Mw getInstance() { + if (instance == null ) { + synchronized (WorldConfig.class) { + if (instance == null) { + instance = new Mw(); + } + } + } + + return instance; + } + + private Mw() { + // client only initialization + this.mc = Minecraft.getMinecraft(); + + // create base save directory + this.saveDir = new File(this.mc.mcDataDir, "saves"); + this.configDir = new File(this.mc.mcDataDir, "config"); + + this.ready = false; + + RegionManager.logger = MwForge.logger; + + ConfigurationHandler.loadConfig(); + } + + public void setTextureSize() { + if (Config.configTextureSize != Config.textureSize) { + int maxTextureSize = Render.getMaxTextureSize(); + int textureSize = 1024; + while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { + textureSize *= 2; + } + textureSize /= 2; + + Logging.log("GL reported max texture size = %d", maxTextureSize); + Logging.log("texture size from config = %d", Config.configTextureSize); + Logging.log("setting map texture size to = %d", textureSize); + + Config.textureSize = textureSize; + if (this.ready) { + // if we are already up and running need to close and reinitialize the map texture and + // region manager. + this.reloadMapTexture(); + } + } + } + + // update the saved player position and orientation + // called every tick + public void updatePlayer() { + // get player pos + this.playerX = (double) this.mc.thePlayer.posX; + this.playerY = (double) this.mc.thePlayer.posY; + this.playerZ = (double) this.mc.thePlayer.posZ; + this.playerXInt = (int) Math.floor(this.playerX); + this.playerYInt = (int) Math.floor(this.playerY); + this.playerZInt = (int) Math.floor(this.playerZ); + + // rotationYaw of 0 points due north, we want it to point due east instead + // so add pi/2 radians (90 degrees) + this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); + this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; + + // set by onWorldLoad + this.playerDimension = this.mc.theWorld.provider.getDimensionId(); + if (this.miniMap.view.getDimension() != this.playerDimension) + { + WorldConfig.getInstance().addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); + } + } + + public void toggleMarkerMode() { + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + } + + // cheap and lazy way to teleport... + public void teleportTo(int x, int y, int z) { + if (Config.teleportEnabled) { + this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void warpTo(String name) { + if (Config.teleportEnabled) { + //MwUtil.printBoth(String.format("warping to %s", name)); + this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void teleportToMapPos(MapView mapView, int x, int y, int z) { + if (!Config.teleportCommand.equals("warp")) { + double scale = mapView.getDimensionScaling(this.playerDimension); + this.teleportTo((int) (x / scale), y, (int) (z / scale)); + } else { + Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); + } + } + + public void teleportToMarker(Marker marker) { + if (Config.teleportCommand.equals("warp")) { + this.warpTo(marker.name); + } else if (marker.dimension == this.playerDimension) { + this.teleportTo(marker.x, marker.y, marker.z); + } else { + Utils.printBoth("cannot teleport to marker in different dimension"); + } + } + + public void loadBlockColourOverrides(BlockColours bc) { + File f = new File(this.configDir, Reference.blockColourOverridesFileName); + if (f.isFile()) { + Logging.logInfo("loading block colour overrides file %s", f); + bc.loadFromFile(f); + } else { + Logging.logInfo("recreating block colour overrides file %s", f); + BlockColours.writeOverridesFile(f); + if (f.isFile()) { + bc.loadFromFile(f); + } else { + Logging.logError("could not load block colour overrides from file %s", f); + } + } + } + + public void saveBlockColours(BlockColours bc) { + File f = new File(this.configDir, Reference.blockColourSaveFileName); + Logging.logInfo("saving block colours to '%s'", f); + bc.saveToFile(f); + } + + public void reloadBlockColours() { + BlockColours bc = new BlockColours(); + File f = new File(this.configDir, Reference.blockColourSaveFileName); + if (Config.useSavedBlockColours && f.isFile()) { + // load block colours from file + Logging.logInfo("loading block colours from %s", f); + bc.loadFromFile(f); + this.loadBlockColourOverrides(bc); + } else { + // generate block colours from current texture pack + Logging.logInfo("generating block colours"); + // block type overrides need to be loaded before the block colours are generated + this.loadBlockColourOverrides(bc); + BlockColourGen.genBlockColours(bc); + // load overrides again to override block and biome colours + this.loadBlockColourOverrides(bc); + this.saveBlockColours(bc); + } + this.blockColours = bc; + } + + public void reloadMapTexture() { + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.executor.close(); + MapTexture oldMapTexture = this.mapTexture; + MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScaling); + this.mapTexture = newMapTexture; + if (oldMapTexture != null) { + oldMapTexture.close(); + } + this.executor = new BackgroundExecutor(); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); + + UndergroundTexture oldTexture = this.undergroundMapTexture; + UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScaling); + this.undergroundMapTexture = newTexture; + if (oldTexture != null) { + this.undergroundMapTexture.close(); + } + } + + public void toggleUndergroundMode() { + Config.undergroundMode = !Config.undergroundMode; + this.miniMap.view.setUndergroundMode(Config.undergroundMode); + } + + //////////////////////////////// + // Initialization and Cleanup + //////////////////////////////// + + public void load() { + + if (this.ready) { + return; + } + + if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { + Logging.log("Mw.load: world or player is null, cannot load yet"); + return; + } + + Logging.log("Mw.load: loading..."); + + // get world and image directories + File saveDir = this.saveDir; + if (Config.saveDirOverride.length() > 0) { + File d = new File(Config.saveDirOverride); + if (d.isDirectory()) { + saveDir = d; + } else { + Logging.log("error: no such directory %s", Config.saveDirOverride); + } + } + + if (this.mc.isSingleplayer()) { + this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), Utils.getWorldName()); + } else { + this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), Utils.getWorldName()); + } + + // create directories + this.imageDir = new File(this.worldDir, "images"); + if (!this.imageDir.exists()) { + this.imageDir.mkdirs(); + } + if (!this.imageDir.isDirectory()) { + Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); + } + + this.tickCounter = 0; + + //this.multiplayer = !this.mc.isIntegratedServerRunning(); + + // marker manager only depends on the config being loaded + this.markerManager = new MarkerManager(); + this.markerManager.load(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); + + this.playerTrail = new Trail(this, Reference.PlayerTrailName); + + // executor does not depend on anything + this.executor = new BackgroundExecutor(); + + // mapTexture depends on config being loaded + this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScaling); + this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScaling); + this.reloadBlockColours(); + // region manager depends on config, mapTexture, and block colours + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); + // overlay manager depends on mapTexture + this.miniMap = new MiniMap(this); + this.miniMap.view.setDimension(this.mc.thePlayer.dimension); + + this.chunkManager = new ChunkManager(this); + + this.ready = true; + + //if (!zoomLevelsExist) { + //printBoth("recreating zoom levels"); + //this.regionManager.recreateAllZoomLevels(); + //} + } + + public void close() { + + Logging.log("Mw.close: closing..."); + + if (this.ready) { + this.ready = false; + + this.chunkManager.close(); + this.chunkManager = null; + + // close all loaded regions, saving modified images. + // this will create extra tasks that need to be completed. + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.regionManager = null; + + Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); + if (this.executor.close()) { + Logging.log("error: timeout waiting for tasks to finish"); + } + Logging.log("done"); + + this.playerTrail.close(); + + this.markerManager.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); + this.markerManager.clear(); + + // close overlay + this.miniMap.close(); + this.miniMap = null; + + this.undergroundMapTexture.close(); + this.mapTexture.close(); + + WorldConfig.getInstance().saveWorldConfig(); + //this.saveConfig(); + + this.tickCounter = 0; + + OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in + } + } + + //////////////////////////////// + // Event handlers + //////////////////////////////// + + public void onTick() { + this.load(); + if (this.ready && (this.mc.thePlayer != null)) { + + this.updatePlayer(); + + if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { + this.undergroundMapTexture.update(); + } + + if (!(this.mc.currentScreen instanceof MwGui)) { + // if in game (no gui screen) center the minimap on the player and render it. + this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); + this.miniMap.drawCurrentMap(); + } + + // process background tasks + int maxTasks = 50; + while (!this.executor.processTaskQueue() && (maxTasks > 0)) { + maxTasks--; + } + + this.chunkManager.onTick(); + + // update GL texture of mapTexture if updated + this.mapTexture.processTextureUpdates(); + + // let the renderEngine know we have changed the bound texture. + //this.mc.renderEngine.resetBoundTexture(); + + //if (this.tickCounter % 100 == 0) { + // MwUtil.log("tick %d", this.tickCounter); + //} + this.playerTrail.onTick(); + + this.tickCounter++; + } + } + + // add chunk to the set of loaded chunks + public void onChunkLoad(Chunk chunk) { + this.load(); + if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + if (this.ready) { + this.chunkManager.addChunk(chunk); + } else { + Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); + } + } + } + + // remove chunk from the set of loaded chunks. + // convert to mwchunk and write chunk to region file if in multiplayer. + public void onChunkUnload(Chunk chunk) { + if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + this.chunkManager.removeChunk(chunk); + } + } + + // from onTick when mc.currentScreen is an instance of GuiGameOver + // it's the only option to detect death client side + public void onPlayerDeath(EntityPlayerMP player) { + if (this.ready && (Config.maxDeathMarkers > 0)) { + this.updatePlayer(); + int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; + for (int i = 0; i < deleteCount; i++) { + // delete the first marker found in the group "playerDeaths". + // as new markers are only ever appended to the marker list this will delete the + // earliest death marker added. + this.markerManager.delMarker(null, "playerDeaths"); + } + + this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); + this.markerManager.setVisibleGroupName("playerDeaths"); + this.markerManager.update(); + } + } + + public void onKeyDown(KeyBinding kb) { + // make sure not in GUI element (e.g. chat box) + if ((this.mc.currentScreen == null) && (this.ready)) { + //Mw.log("client tick: %s key pressed", kb.keyDescription); + + if (kb == MwKeyHandler.keyMapMode) { + // map mode toggle + this.miniMap.nextOverlayMode(1); + + } else if (kb == MwKeyHandler.keyMapGui) { + // open map gui + this.mc.displayGuiScreen(new MwGui(this)); + + } else if (kb == MwKeyHandler.keyNewMarker) { + // open new marker dialog + String group = this.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + null, + this.markerManager, + "", + group, + this.playerXInt, + this.playerYInt, + this.playerZInt, + this.playerDimension + ) + ); + + } else if (kb == MwKeyHandler.keyNextGroup) { + // toggle marker mode + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + + } else if (kb == MwKeyHandler.keyTeleport) { + // set or remove marker + Marker marker = this.markerManager.getNearestMarkerInDirection( + this.playerXInt, + this.playerZInt, + this.playerHeading); + if (marker != null) { + this.teleportToMarker(marker); + } + } else if (kb == MwKeyHandler.keyZoomIn) { + // zoom in + this.miniMap.view.adjustZoomLevel(-1); + } else if (kb == MwKeyHandler.keyZoomOut) { + // zoom out + this.miniMap.view.adjustZoomLevel(1); + } else if (kb == MwKeyHandler.keyUndergroundMode) { + this.toggleUndergroundMode(); + } + } + } +} diff --git a/src/main/java/mapwriter/util/Config.java b/src/main/java/mapwriter/config/Config.java similarity index 87% rename from src/main/java/mapwriter/util/Config.java rename to src/main/java/mapwriter/config/Config.java index 5b4dcae0..f750bbd0 100644 --- a/src/main/java/mapwriter/util/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -1,60 +1,61 @@ -package mapwriter.util; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class Config { - public static final String[] miniMapPositionStringArray = { - "unchanged", - "top right", - "top left", - "bottom right", - "bottom left" - }; - public static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; - public static final String[] backgroundModeStringArray = { - "none", - "static", - "panning" - }; - - // configuration options - public static boolean linearTextureScalingEnabled = true; - public static String coordsMode = coordsModeStringArray[0]; - public static boolean undergroundMode = false; - public static boolean teleportEnabled = true; - public static String teleportCommand = "tp"; - public static int defaultTeleportHeight = 80; - public static int maxZoom = 5; - public static int minZoom = -5; - public static boolean useSavedBlockColours = false; - public static int maxChunkSaveDistSq = 128 * 128; - public static boolean mapPixelSnapEnabled = true; - public static int textureSize = 2048; - public static int configTextureSize = 2048; - public static int maxDeathMarkers = 3; - public static int chunksPerTick = 5; - public static boolean portNumberInWorldNameEnabled = true; - public static String saveDirOverride = ""; - public static boolean regionFileOutputEnabledSP = true; - public static boolean regionFileOutputEnabledMP = true; - public static int backgroundTextureMode = 0; - - //World configuration Options - public static int modeIndex = 0; - public static int zoomLevel = 0; - - public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); - public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); - public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); -} +package mapwriter.config; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.util.Reference; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class Config { + public static final String[] miniMapPositionStringArray = { + "unchanged", + "top right", + "top left", + "bottom right", + "bottom left" + }; + public static final String[] coordsModeStringArray = { + "disabled", + "small", + "large" + }; + public static final String[] backgroundModeStringArray = { + "none", + "static", + "panning" + }; + + // configuration options + public static boolean linearTextureScaling = true; + public static String coordsMode = coordsModeStringArray[0]; + public static boolean undergroundMode = false; + public static boolean teleportEnabled = true; + public static String teleportCommand = "tp"; + public static int defaultTeleportHeight = 80; + public static int zoomOutLevels = 5; + public static int zoomInLevels = -5; + public static boolean useSavedBlockColours = false; + public static int maxChunkSaveDistSq = 128 * 128; + public static boolean mapPixelSnapEnabled = true; + public static int textureSize = 2048; + public static int configTextureSize = 2048; + public static int maxDeathMarkers = 3; + public static int chunksPerTick = 5; + public static boolean portNumberInWorldNameEnabled = true; + public static String saveDirOverride = ""; + public static boolean regionFileOutputEnabledSP = true; + public static boolean regionFileOutputEnabledMP = true; + public static int backgroundTextureMode = 0; + + //World configuration Options + public static int overlayModeIndex = 0; + public static int overlayZoomLevel = 0; + + public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); + public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); + public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); +} diff --git a/src/main/java/mapwriter/util/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java similarity index 75% rename from src/main/java/mapwriter/util/MapModeConfig.java rename to src/main/java/mapwriter/config/MapModeConfig.java index afa1bf95..2349f2ce 100644 --- a/src/main/java/mapwriter/util/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -1,64 +1,65 @@ -package mapwriter.util; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class MapModeConfig { - - public final String configCategory; - - public boolean enabled = true; - public boolean rotate = true; - public boolean circular = true; - public boolean coordsEnabled = false; - public int borderMode = 1; - public int playerArrowSize = 5; - public int markerSize = 5; - public int trailMarkerSize = 3; - public int alphaPercent = 100; - - public int marginTop = 0; - public int marginBottom = 0; - public int marginLeft = 0; - public int marginRight = 0; - public int heightPercent = -1; - - public MapModeConfig(String configCategory) { - this.configCategory = configCategory; - } - - public void loadConfig() { - // get options from config file - this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, ""); - this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, ""); - this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, ""); - this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, ""); - - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, ""); - this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, ""); - this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, ""); - this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, ""); - this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, ""); - - this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, ""); - this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, ""); - this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, ""); - this.borderMode = ConfigurationHandler.configuration.getInt("borderMode", this.configCategory, this.borderMode, 0, 1, ""); - - this.trailMarkerSize = Math.max(1, this.markerSize - 1); - } - - public IConfigElement categoryElement(String name, String tooltip_key) - { - ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); - } -} +package mapwriter.config; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class MapModeConfig { + + public final String configCategory; + + public boolean enabled = true; + public boolean rotate = true; + public boolean circular = true; + public boolean coordsEnabled = false; + public boolean borderMode = true; + public int playerArrowSize = 5; + public int markerSize = 5; + public int trailMarkerSize = 3; + public int alphaPercent = 100; + + public int marginTop = 0; + public int marginBottom = 0; + public int marginLeft = 0; + public int marginRight = 0; + public int heightPercent = -1; + + public MapModeConfig(String configCategory) { + this.configCategory = configCategory; + } + + public void loadConfig() { + // get options from config file + this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, "mw.config.map.enabled"); + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, "mw.config.map.playerArrowSize"); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, "mw.config.map.markerSize"); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, "mw.config.map.alphaPercent"); + + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, "mw.config.map.heightPercent"); + this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, "mw.config.map.marginTop"); + this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, "mw.config.map.marginBottom"); + this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, "mw.config.map.marginLeft"); + this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, "mw.config.map.marginRight"); + + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, "mw.config.map.rotate"); + this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, "mw.config.map.circular"); + this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, "mw.config.map.coordsEnabled"); + this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderMode, "mw.config.map.borderMode"); + + this.trailMarkerSize = Math.max(1, this.markerSize - 1); + } + + public IConfigElement categoryElement(String name, String tooltip_key) + { + ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); + + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); + } +} diff --git a/src/main/java/mapwriter/config/WorldConfig.java b/src/main/java/mapwriter/config/WorldConfig.java new file mode 100644 index 00000000..599f0b59 --- /dev/null +++ b/src/main/java/mapwriter/config/WorldConfig.java @@ -0,0 +1,71 @@ +package mapwriter.config; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraftforge.common.config.Configuration; + +public class WorldConfig +{ + private static WorldConfig instance = null; + + public Configuration worldConfiguration = null; + + // list of available dimensions + public List dimensionList = new ArrayList(); + + private WorldConfig() + { + // load world specific config file + File worldConfigFile = new File(Mw.getInstance().worldDir, Reference.worldDirConfigName); + this.worldConfiguration = new Configuration(worldConfigFile); + + InitDimensionList(); + } + + public static WorldConfig getInstance() { + if (instance == null ) { + synchronized (WorldConfig.class) { + if (instance == null) { + instance = new WorldConfig(); + } + } + } + + return instance; + } + + public void saveWorldConfig() + { + this.worldConfiguration.save(); + } + + //Dimension List + public void InitDimensionList() + { + dimensionList.clear(); + this.worldConfiguration.get(Reference.catWorld, "dimensionList", Utils.integerListToIntArray(dimensionList)); + addDimension(0); + cleanDimensionList(); + } + + public void addDimension(int dimension) { + int i = dimensionList.indexOf(dimension); + if (i < 0) { + dimensionList.add(dimension); + } + } + + public void cleanDimensionList() { + List dimensionListCopy = new ArrayList(dimensionList); + dimensionList.clear(); + for (int dimension : dimensionListCopy) { + this.addDimension(dimension); + } + } + +} diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 75480f65..31012b9e 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -19,8 +19,7 @@ public void preInit(File configFile) } public void load() { - Mw mw = new Mw(); - MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); + MinecraftForge.EVENT_BUS.register(new EventHandler(Mw.getInstance())); Object eventhandler = new MwKeyHandler(); FMLCommonHandler.instance().bus().register(eventhandler); diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 8e2946c4..824d6099 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -77,7 +77,7 @@ public void eventPlayerDeath(LivingDeathEvent event) { @SubscribeEvent public void renderMap(RenderGameOverlayEvent.Post event){ if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - Mw.instance.onTick(); + Mw.getInstance().onTick(); } } } diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index 0e04f98a..0c2eeb76 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -1,7 +1,5 @@ package mapwriter.forge; -import java.net.InetSocketAddress; - import mapwriter.Mw; import mapwriter.util.Reference; import net.minecraft.client.Minecraft; @@ -15,18 +13,17 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraftforge.fml.common.network.FMLNetworkEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -@Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS ) +@Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS, clientSideOnly=true ) public class MwForge { @Instance(Reference.MOD_ID) public static MwForge instance; - @SidedProxy(clientSide=Reference.CLIENT_PROXY_CLASS, serverSide=Reference.CLIENT_PROXY_CLASS) + @SidedProxy(clientSide=Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; public static Logger logger = LogManager.getLogger(Reference.MOD_ID); @@ -47,21 +44,13 @@ public void postInit(FMLPostInitializationEvent event) { proxy.postInit(); } - @SubscribeEvent - public void onConnected(FMLNetworkEvent.ClientConnectedToServerEvent event){ - if (!event.isLocal) { - InetSocketAddress address = (InetSocketAddress) event.manager.getRemoteAddress(); - Mw.instance.setServerDetails(address.getHostName(), address.getPort()); - } - } - @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event){ if (event.phase == TickEvent.Phase.START){ // run the cleanup code when Mw is loaded and the player becomes null. // a bit hacky, but simpler than checking if the connection has closed. - if ((Mw.instance.ready) && (Minecraft.getMinecraft().thePlayer == null)) { - Mw.instance.close(); + if ((Mw.getInstance().ready) && (Minecraft.getMinecraft().thePlayer == null)) { + Mw.getInstance().close(); } } } diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index fad2f9c6..a7814d1a 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -71,7 +71,7 @@ public void keyEvent(InputEvent.KeyInputEvent event) @SubscribeEvent public void keyEventSpecial(KeyBindingPressedEvent event) { - Mw.instance.onKeyDown(event.keyBinding); + Mw.getInstance().onKeyDown(event.keyBinding); } private void checkKeys() @@ -80,7 +80,7 @@ private void checkKeys() { if (key != null && key.isPressed()) { - Mw.instance.onKeyDown(key); + Mw.getInstance().onKeyDown(key); } } } diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index e731fae4..a7f79faa 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -1,163 +1,163 @@ -package mapwriter.gui; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Config; -import mapwriter.util.Reference; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.AddModOverrideEntry; -import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.ModOverridesEntry; -import net.minecraftforge.common.ForgeChunkManager; -import net.minecraftforge.common.config.ConfigCategory; -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.GuiConfig; -import net.minecraftforge.fml.client.config.GuiConfigEntries; -import net.minecraftforge.fml.client.config.GuiUtils; -import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; -import net.minecraftforge.fml.client.config.IConfigElement; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; -import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.CategoryEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.NumberSliderEntry; - -public class ModGuiConfig extends GuiConfig -{ - public ModGuiConfig(GuiScreen guiScreen) - { - super(guiScreen, - getConfigElements(), - //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), - Reference.MOD_ID, - "Options", - false, - false, - GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); - } - - /** Compiles a list of config elements */ - private static List getConfigElements() - { - List list = new ArrayList(); - - //Add categories to config GUI - list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); - list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); - list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); - list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); - return list; - } - - /** Creates a button linking to another screen where all options of the category are available */ - private static IConfigElement categoryElement(String category, String name, String tooltip_key) - { - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); - } - - public static class ModBooleanEntry extends ButtonEntry - { - protected final boolean beforeValue; - protected boolean currentValue; - - public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) - { - super(owningScreen, owningEntryList, configElement); - this.beforeValue = Boolean.valueOf(configElement.get().toString()); - this.currentValue = beforeValue; - this.btnValue.enabled = enabled(); - updateValueButtonText(); - } - - @Override - public void updateValueButtonText() - { - this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); - btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); - } - - @Override - public void valueButtonPressed(int slotIndex) - { - if (enabled()) - currentValue = !currentValue; - } - - @Override - public boolean isDefault() - { - return currentValue == Boolean.valueOf(configElement.getDefault().toString()); - } - - @Override - public void setToDefault() - { - if (enabled()) - { - currentValue = Boolean.valueOf(configElement.getDefault().toString()); - updateValueButtonText(); - } - } - - @Override - public boolean isChanged() - { - return currentValue != beforeValue; - } - - @Override - public void undoChanges() - { - if (enabled()) - { - currentValue = beforeValue; - updateValueButtonText(); - } - } - - @Override - public boolean saveConfigElement() - { - if (enabled() && isChanged()) - { - configElement.set(currentValue); - return configElement.requiresMcRestart(); - } - return false; - } - - @Override - public Boolean getCurrentValue() - { - return currentValue; - } - - @Override - public Boolean[] getCurrentValues() - { - return new Boolean[] { getCurrentValue() }; - } - - @Override - public boolean enabled() - { - for (IConfigEntry entry : this.owningEntryList.listEntries) - { - if (entry.getName().equals("circular") && entry instanceof BooleanEntry) - { - return Boolean.valueOf(entry.getCurrentValue().toString()); - } - } - - return true; - } - } -} +package mapwriter.gui; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import mapwriter.config.Config; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Reference; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.AddModOverrideEntry; +import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.ModOverridesEntry; +import net.minecraftforge.common.ForgeChunkManager; +import net.minecraftforge.common.config.ConfigCategory; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.GuiConfigEntries; +import net.minecraftforge.fml.client.config.GuiUtils; +import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; +import net.minecraftforge.fml.client.config.IConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.CategoryEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.NumberSliderEntry; + +public class ModGuiConfig extends GuiConfig +{ + public ModGuiConfig(GuiScreen guiScreen) + { + super(guiScreen, + getConfigElements(), + //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + Reference.MOD_ID, + "Options", + false, + false, + GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); + } + + /** Compiles a list of config elements */ + private static List getConfigElements() + { + List list = new ArrayList(); + + //Add categories to config GUI + list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); + list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); + list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); + list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); + return list; + } + + /** Creates a button linking to another screen where all options of the category are available */ + private static IConfigElement categoryElement(String category, String name, String tooltip_key) + { + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); + } + + public static class ModBooleanEntry extends ButtonEntry + { + protected final boolean beforeValue; + protected boolean currentValue; + + public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) + { + super(owningScreen, owningEntryList, configElement); + this.beforeValue = Boolean.valueOf(configElement.get().toString()); + this.currentValue = beforeValue; + this.btnValue.enabled = enabled(); + updateValueButtonText(); + } + + @Override + public void updateValueButtonText() + { + this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); + btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); + } + + @Override + public void valueButtonPressed(int slotIndex) + { + if (enabled()) + currentValue = !currentValue; + } + + @Override + public boolean isDefault() + { + return currentValue == Boolean.valueOf(configElement.getDefault().toString()); + } + + @Override + public void setToDefault() + { + if (enabled()) + { + currentValue = Boolean.valueOf(configElement.getDefault().toString()); + updateValueButtonText(); + } + } + + @Override + public boolean isChanged() + { + return currentValue != beforeValue; + } + + @Override + public void undoChanges() + { + if (enabled()) + { + currentValue = beforeValue; + updateValueButtonText(); + } + } + + @Override + public boolean saveConfigElement() + { + if (enabled() && isChanged()) + { + configElement.set(currentValue); + return configElement.requiresMcRestart(); + } + return false; + } + + @Override + public Boolean getCurrentValue() + { + return currentValue; + } + + @Override + public Boolean[] getCurrentValues() + { + return new Boolean[] { getCurrentValue() }; + } + + @Override + public boolean enabled() + { + for (IConfigEntry entry : this.owningEntryList.listEntries) + { + if (entry.getName().equals("circular") && entry instanceof BooleanEntry) + { + return Boolean.valueOf(entry.getCurrentValue().toString()); + } + } + + return true; + } + } +} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 352e2a70..0989edff 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,646 +1,647 @@ -package mapwriter.gui; - -import java.awt.Point; -import java.io.IOException; - -import mapwriter.Mw; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import mapwriter.util.Config; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.util.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - public MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - - public static MwGui instance; - - class Label { - int x = 0, y = 0, w = 1, h = 12; - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); - } - } - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - this.mapView.setZoomLevel(0); - - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - - instance = this; - } - - public MwGui(Mw mw, int dim, int x, int z){ - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(0); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - public void exitGui() { - //MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); - this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), - (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension(), - this.mw.worldDir, - this.mw.worldDir.getName())); - - Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); - } - - public void regenerateView() { - Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ())); - this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask( - this.mw, - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch(key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, - 0 - ); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen( - new MwGuiTeleportDialog( - this, - this.mw, - this.mapView, - this.mouseBlockX, - Config.defaultTeleportHeight, - this.mouseBlockZ - ) - ); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - //case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(Config.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) - { - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen( - new MwGuiDimensionDialog( - this, - this.mw, - this.mapView, - this.mapView.getDimension() - ) - ); - } else if (this.optionsLabel.posWithin(x, y)) - { - try - { - GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); - this.mc.displayGuiScreen(newScreen); - } - catch (Exception e) - { - Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); - } - - //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - //this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - marker - ) - ); - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - //this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { - //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - //this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(this.mw.dimensionList, n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); - } - } - - // called every frame - public void updateScreen() { - //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) { - String s; - if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); - } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); - } - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { - s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); - } - } - - /*if (this.mw.markerManager.selectedMarker != null) { - s += ", current marker: " + this.mw.markerManager.selectedMarker.name; - }*/ - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); - this.drawCenteredString(this.fontRendererObj, - s, this.width / 2, this.height - 18, 0xffffff); - } - - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max( - this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, - title, - x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, - desc, - x + 10, y + 4, 0xcccccc); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - //double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - //this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); - } - - super.drawScreen(mouseX, mouseY, f); - } -} - +package mapwriter.gui; + +import java.awt.Point; +import java.io.IOException; + +import mapwriter.Mw; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + public MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private int exit = 0; + + private Label helpLabel; + private Label optionsLabel; + private Label dimensionLabel; + private Label groupLabel; + private Label overlayLabel; + + public static MwGui instance; + + class Label { + int x = 0, y = 0, w = 1, h = 12; + public Label() { + } + + public void draw(int x, int y, String s) { + this.x = x; + this.y = y; + this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; + MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); + MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); + } + + public void drawToRightOf(Label label, String s) { + this.draw(label.x + label.w + 5, label.y, s); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); + } + } + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(); + this.mapView = new MapView(this.mw); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + this.mapView.setZoomLevel(0); + + this.helpLabel = new Label(); + this.optionsLabel = new Label(); + this.dimensionLabel = new Label(); + this.groupLabel = new Label(); + this.overlayLabel = new Label(); + + instance = this; + } + + public MwGui(Mw mw, int dim, int x, int z){ + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(0); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() { + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) { + + } + + public void exitGui() { + //MwUtil.log("closing GUI"); + // set the mini map dimension to the GUI map dimension when closing + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + this.mc.getSoundHandler().resumeSounds(); + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); + if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); + this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), + (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension(), + this.mw.worldDir, + this.mw.worldDir.getName())); + + Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); + } + + public void regenerateView() { + Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ())); + this.mw.reloadBlockColours(); + this.mw.executor.addTask2(new RebuildRegionsTask( + this.mw, + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch(key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, + 0 + ); + } + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen( + new MwGuiTeleportDialog( + this, + this.mw, + this.mapView, + this.mouseBlockX, + Config.defaultTeleportHeight, + this.mouseBlockZ + ) + ); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + //case Keyboard.KEY_9: + // MwUtil.log("refreshing maptexture"); + // this.mw.mapTexture.updateTexture(); + // break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + // exit on the next tick + this.exit = 1; + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(Config.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) + return; + + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) + { + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen( + new MwGuiDimensionDialog( + this, + this.mw, + this.mapView, + this.mapView.getDimension() + ) + ); + } else if (this.optionsLabel.posWithin(x, y)) + { + try + { + GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } + catch (Exception e) + { + Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); + } + + //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + //this.mouseRightHeld = 1; + if ((marker != null) && (prevMarker == marker)) { + // right clicked previously selected marker. + // edit the marker + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + marker + ) + ); + + } else if (marker == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(x, y)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + "", + group, + mx, my, mz, + this.mapView.getDimension() + ) + ); + } + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + //this.viewSizeStart = this.mapManager.getViewSize(); + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseReleased(int x, int y, int button) { + //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + //this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); + } + } + + // called every frame + public void updateScreen() { + //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); + // need to wait one tick before exiting so that the game doesn't + // handle the 'm' key and re-open the gui. + // there should be a better way. + if (this.exit > 0) { + this.exit++; + } + if (this.exit > 2) { + this.exitGui(); + } + super.updateScreen(); + } + + public void drawStatus(int bX, int bY, int bZ) { + String s; + if (bY != 0) { + s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + } else { + s = String.format("cursor: (%d, ?, %d)", bX, bZ); + } + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { + s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); + } + } + + /*if (this.mw.markerManager.selectedMarker != null) { + s += ", current marker: " + this.mw.markerManager.selectedMarker.name; + }*/ + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); + + drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); + this.drawCenteredString(this.fontRendererObj, + s, this.width / 2, this.height - 18, 0xffffff); + } + + public void drawHelp() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString( + "Keys:\n\n" + + " Space\n" + + " Delete\n" + + " C\n" + + " Home\n" + + " End\n" + + " N\n" + + " T\n" + + " P\n" + + " R\n" + + " U\n\n" + + "Left click drag or arrow keys pan the map.\n" + + "Mouse wheel or Page Up/Down zooms map.\n" + + "Right click map to create a new marker.\n" + + "Left click drag a selected marker to move it.\n" + + "Mouse wheel over selected marker to cycle colour.\n" + + "Mouse wheel over dimension or group box to cycle.\n", + 15, 24, this.width - 30, 0xffffff); + this.fontRendererObj.drawSplitString( + "| Next marker group\n" + + "| Delete selected marker\n" + + "| Cycle selected marker colour\n" + + "| Centre map on player\n" + + "| Centre map on selected marker\n" + + "| Select next marker\n" + + "| Teleport to cursor or selected marker\n" + + "| Save PNG of visible map area\n" + + "| Regenerate visible map area from region files\n" + + "| Underground map mode\n", + 75, 42, this.width - 90, 0xffffff); + } + + public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { + String desc = String.format("(%d, %d, %d)", mX, mY, mZ); + int stringW = Math.max( + this.fontRendererObj.getStringWidth(title), + this.fontRendererObj.getStringWidth(desc)); + + x = Math.min(x, this.width - (stringW + 16)); + y = Math.min(Math.max(10, y), this.height - 14); + + drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); + this.drawString(this.fontRendererObj, + title, + x + 10, y - 8, 0xffffff); + this.drawString(this.fontRendererObj, + desc, + x + 10, y + 4, 0xcccccc); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + //double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + //this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(menuX, menuY, "[help]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); + String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + this.drawHelp(); + } + + super.drawScreen(mouseX, mouseY, f); + } +} + diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java index 6fca1941..7dbf02c5 100644 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -1,6 +1,7 @@ package mapwriter.gui; import mapwriter.Mw; +import mapwriter.config.WorldConfig; import mapwriter.map.MapView; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; @@ -27,7 +28,7 @@ public boolean submit() { if (this.inputValid) { this.mapView.setDimensionAndAdjustZoom(dimension); this.mw.miniMap.view.setDimension(dimension); - this.mw.addDimension(dimension); + WorldConfig.getInstance().addDimension(dimension); done = true; } return done; diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index 41dda883..bdb713e0 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -1,8 +1,8 @@ package mapwriter.gui; import mapwriter.Mw; +import mapwriter.config.Config; import mapwriter.map.MapView; -import mapwriter.util.Config; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; diff --git a/src/main/java/mapwriter/handler/ConfigurationHandler.java b/src/main/java/mapwriter/handler/ConfigurationHandler.java index 065527b8..0a67b082 100644 --- a/src/main/java/mapwriter/handler/ConfigurationHandler.java +++ b/src/main/java/mapwriter/handler/ConfigurationHandler.java @@ -1,121 +1,125 @@ -package mapwriter.handler; - -import java.io.File; - -import mapwriter.util.Config; -import mapwriter.util.Reference; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.fml.client.event.ConfigChangedEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - - public class ConfigurationHandler - { - public static Configuration configuration; - - public static void init(File configFile) - { - // Create the configuration object from the given configuration file - if (configuration == null) - { - configuration = new Configuration(configFile); - setMapModeDefaults(); - loadConfig(); - } - } - - public static void loadConfig() - { - Config.linearTextureScalingEnabled = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingEnabled, ""); - Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, ""); - Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, ""); - Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, ""); - Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "", Config.coordsModeStringArray); - Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, ""); - Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, ""); - Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, ""); - Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, ""); - Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, ""); - Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, ""); - Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, ""); - Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, ""); - Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, ""); - Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, ""); - - Config.maxZoom = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.maxZoom, 1, 256, ""); - Config.minZoom = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.minZoom, 1, 256, ""); - - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, ""); - - Config.fullScreenMap.loadConfig(); - Config.largeMap.loadConfig(); - Config.smallMap.loadConfig(); - - if (configuration.hasChanged()) - { - configuration.save(); - } - - //Mw.instance.setTextureSize(); - } - - public static void loadWorldConfig() - { - // load config file options - Config.modeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.modeIndex, 0, 1000, ""); - Config.zoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.minZoom, Config.maxZoom, ""); - } - - @SubscribeEvent - public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) - { - if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) - { - loadConfig(); - } - } - - public static void setMapModeDefaults() - { - Config.fullScreenMap.heightPercent = -1; - Config.fullScreenMap.marginTop = 0; - Config.fullScreenMap.marginBottom = 0; - Config.fullScreenMap.marginLeft = 0; - Config.fullScreenMap.marginRight = 0; - Config.fullScreenMap.borderMode = 0; - Config.fullScreenMap.playerArrowSize = 5; - Config.fullScreenMap.markerSize = 5; - Config.fullScreenMap.alphaPercent = 100; - Config.fullScreenMap.rotate = false; - Config.fullScreenMap.circular = false; - Config.fullScreenMap.coordsEnabled = false; - - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); - - Config.largeMap.heightPercent = -1; - Config.largeMap.marginTop = 10; - Config.largeMap.marginBottom = 40; - Config.largeMap.marginLeft = 40; - Config.largeMap.marginRight = 40; - Config.largeMap.playerArrowSize = 5; - Config.largeMap.markerSize = 5; - Config.largeMap.coordsEnabled = true; - - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); - - Config.smallMap.heightPercent = 30; - Config.smallMap.marginTop = 10; - Config.smallMap.marginBottom = -1; - Config.smallMap.marginLeft = -1; - Config.smallMap.marginRight = 10; - Config.smallMap.playerArrowSize = 4; - Config.smallMap.markerSize = 3; - Config.smallMap.coordsEnabled = true; - } +package mapwriter.handler; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.client.event.ConfigChangedEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + + public class ConfigurationHandler + { + // configuration files (global and world specific) + public static Configuration configuration; + + public static void init(File configFile) + { + // Create the configuration object from the given configuration file + if (configuration == null) + { + configuration = new Configuration(configFile); + setMapModeDefaults(); + loadConfig(); + } + } + + public static void loadConfig() + { + Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScaling, "mw.config.linearTextureScaling"); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, "mw.config.useSavedBlockColours"); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, "mw.config.teleportEnabled"); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, "mw.config.teleportCommand"); + Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "mw.config.coordsMode", Config.coordsModeStringArray); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, "mw.config.mapPixelSnapEnabled"); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, "mw.config.maxDeathMarkers"); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, "mw.config.chunksPerTick"); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, "mw.config.saveDirOverride"); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, "mw.config.portNumberInWorldNameEnabled"); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, "mw.config.undergroundMode"); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, "mw.config.regionFileOutputEnabledSP"); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, "mw.config.regionFileOutputEnabledMP"); + Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, "mw.config.backgroundTextureMode"); + + Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevels, 1, 256, "mw.config.zoomOutLevels"); + Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevels, 1, 256, "mw.config.zoomInLevels"); + + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, "mw.config.textureSize"); + + Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndex, 0, 1000, "mw.config.overlayModeIndex"); + Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); + + Config.fullScreenMap.loadConfig(); + Config.largeMap.loadConfig(); + Config.smallMap.loadConfig(); + + if (configuration.hasChanged()) + { + configuration.save(); + //Mw.getInstance().setTextureSize(); + } + } + + + @SubscribeEvent + public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) + { + if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) + { + loadConfig(); + } + } + + public static void setMapModeDefaults() + { + Config.fullScreenMap.heightPercent = -1; + Config.fullScreenMap.marginTop = 0; + Config.fullScreenMap.marginBottom = 0; + Config.fullScreenMap.marginLeft = 0; + Config.fullScreenMap.marginRight = 0; + Config.fullScreenMap.borderMode = false; + Config.fullScreenMap.playerArrowSize = 5; + Config.fullScreenMap.markerSize = 5; + Config.fullScreenMap.alphaPercent = 100; + Config.fullScreenMap.rotate = false; + Config.fullScreenMap.circular = false; + Config.fullScreenMap.coordsEnabled = false; + + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "enabled", Config.fullScreenMap.enabled).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); + + Config.largeMap.heightPercent = -1; + Config.largeMap.marginTop = 10; + Config.largeMap.marginBottom = 40; + Config.largeMap.marginLeft = 40; + Config.largeMap.marginRight = 40; + Config.largeMap.playerArrowSize = 5; + Config.largeMap.markerSize = 5; + Config.largeMap.coordsEnabled = true; + + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", Config.largeMap.enabled).setRequiresWorldRestart(true); + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); + + Config.smallMap.heightPercent = 30; + Config.smallMap.marginTop = 10; + Config.smallMap.marginBottom = -1; + Config.smallMap.marginLeft = -1; + Config.smallMap.marginRight = 10; + Config.smallMap.playerArrowSize = 4; + Config.smallMap.markerSize = 3; + Config.smallMap.coordsEnabled = true; + + ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", Config.smallMap.enabled).setRequiresWorldRestart(true); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 63ec6f4a..6a12ac19 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -1,320 +1,325 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.Mw; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Config; -import mapwriter.util.Render; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -public class MapRenderer { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - // accessed by the MwGui to check whether the mouse cursor is near the - // player arrow on the rendered map - public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { - this.mw = mw; - this.mapMode = mapMode; - this.mapView = mapView; - } - - private void drawMap() { - - int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) Config.textureSize; - double zoomScale = (double) (1 << regionZoomLevel); - - // if the texture UV coordinates do not line up with the texture pixels then the texture - // will look blurry when it is drawn to the screen. - // to fix this we round the texture coordinates to the nearest pixel boundary. - // this is unnecessary when zoomed in as the texture will be upscaled and look blurry - // anyway, so it is disabled in this case. - // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture - // pixel boundaries when zoomed in. - - double u, v, w, h; - if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { - u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; - v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; - w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; - h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; - } else { - double tSizeInBlocks = tSize * zoomScale; - u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; - v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; - w = (this.mapView.getWidth() / tSizeInBlocks); - h = (this.mapView.getHeight() / tSizeInBlocks); - } - - GL11.glPushMatrix(); - - if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - if (this.mapMode.config.circular) { - Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); - } - - if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { - // draw the underground map - this.mw.undergroundMapTexture.requestView(this.mapView); - // underground map needs to have a black background - Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - this.mw.undergroundMapTexture.bind(); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } else { - // draw the surface map - MapViewRequest req = new MapViewRequest(this.mapView); - this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); - - // draw the background texture - if (Config.backgroundTextureMode > 0) { - double bu1 = 0.0; double bu2 = 1.0; - double bv1 = 0.0; double bv2 = 1.0; - if (Config.backgroundTextureMode == 2) { - // background moves with map if mode is 2 - double bSize = tSize / 256.0; - bu1 = u * bSize; bu2 = (u + w) * bSize; - bv1 = v * bSize; bv2 = (v + h) * bSize; - } - this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - bu1, bv1, bu2, bv2 - ); - } else { - // mode 0, no background texture - Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - } - - // only draw surface map if the request is loaded (view requests are - // loaded by the background thread) - if (this.mw.mapTexture.isLoaded(req)) { - this.mw.mapTexture.bind(); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } - } - - // draw ProfMobius chunk overlay - IMwDataProvider provider = this.drawOverlay(); - - // overlay onDraw event - if (provider != null) { - GL11.glPushMatrix(); - provider.onDraw(this.mapView, this.mapMode); - GL11.glPopMatrix(); - } - - if (this.mapMode.config.circular) { - Render.disableStencil(); - } - - GL11.glPopMatrix(); - } - - private void drawBorder() { - if (this.mapMode.config.circular) { - this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); - } else { - this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); - } - Render.setColour(0xffffffff); - Render.drawTexturedRect( - this.mapMode.x / 0.75, this.mapMode.y / 0.75, - this.mapMode.w / 0.75, this.mapMode.h / 0.75, - 0.0, 0.0, 1.0, 1.0 - ); - } - - private void drawPlayerArrow() { - GL11.glPushMatrix(); - double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); - Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); - this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); - - // the arrow only needs to be rotated if the map is NOT rotated - GL11.glTranslated(p.x, p.y, 0.0); - if (!this.mapMode.config.rotate) { - GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - double arrowSize = this.mapMode.config.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); - Render.drawTexturedRect( - -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - GL11.glPopMatrix(); - } - - private void drawIcons() { - GL11.glPushMatrix(); - - if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - // draw markers - this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); - - // draw player trail - if (this.mw.playerTrail.enabled) { - this.mw.playerTrail.draw(this.mapMode, this.mapView); - } - - // draw north arrow - if (this.mapMode.config.rotate) { - double y = this.mapMode.h / 2.0; - double arrowSize = this.mapMode.config.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); - Render.drawTexturedRect( - -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - } - - GL11.glPopMatrix(); - - // outside of the matrix pop as theplayer arrow - // needs to be drawn without rotation - this.drawPlayerArrow(); - } - - private void drawCoords() { - // draw coordinates - if (this.mapMode.config.coordsEnabled) { - GL11.glPushMatrix(); - GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (Config.coordsMode != Config.coordsModeStringArray[2]) { - GL11.glScalef(0.5f, 0.5f, 1.0f); - } - int offset = 0; - if (Config.coordsMode != Config.coordsModeStringArray[0]) { - Render.drawCentredString(0, 0, this.mapMode.textColour, - "%d, %d, %d", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt - ); - offset += 12; - } - if (Config.undergroundMode) { - Render.drawCentredString( - 0, offset, this.mapMode.textColour,"underground mode" - ); - } - GL11.glPopMatrix(); - } - } - - private IMwDataProvider drawOverlay() { - // draw overlays from registered providers - //for (IMwDataProvider provider : MwAPI.getDataProviders()) - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) { - ArrayList overlays = provider.getChunksOverlay( - this.mapView.getDimension(), - this.mapView.getX(), this.mapView.getZ(), - this.mapView.getMinX(), this.mapView.getMinZ(), - this.mapView.getMaxX(), this.mapView.getMaxZ() - ); - if (overlays != null) { - for (IMwChunkOverlay overlay : overlays) { - paintChunk(this.mapMode, this.mapView, overlay); - } - } - } - return provider; - } - - public void draw() { - - this.mapMode.setScreenRes(); - this.mapView.setMapWH(this.mapMode); - this.mapView.setTextureSize(Config.textureSize); - - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - - // translate to center of minimap - // z is -2000 so that it is drawn above the 3D world, but below GUI - // elements which are typically at -3000 - GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); - - // draw background, the map texture, and enabled overlays - this.drawMap(); - - if (this.mapMode.config.borderMode > 0) { - this.drawBorder(); - } - this.drawIcons(); - - this.drawCoords(); - - // some shader mods seem to need depth testing re-enabled - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); - } - - private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ - int chunkX = overlay.getCoordinates().x; - int chunkZ = overlay.getCoordinates().y; - float filling = overlay.getFilling(); - - Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); - Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); - - topCorner.x = Math.max(mapMode.x, topCorner.x); - topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); - topCorner.y = Math.max(mapMode.y, topCorner.y); - topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); - - botCorner.x = Math.max(mapMode.x, botCorner.x); - botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); - botCorner.y = Math.max(mapMode.y, botCorner.y); - botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); - - double sizeX = (botCorner.x - topCorner.x) * filling; - double sizeY = (botCorner.y - topCorner.y) * filling; - double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; - double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; - - if (overlay.hasBorder()) { - Render.setColour(overlay.getBorderColor()); - Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); - } - - Render.setColour(overlay.getColor()); - Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); - } -} - +package mapwriter.map; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.Mw; +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Render; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +public class MapRenderer { + private Mw mw; + private MapMode mapMode; + private MapView mapView; + // accessed by the MwGui to check whether the mouse cursor is near the + // player arrow on the rendered map + public Point.Double playerArrowScreenPos = new Point.Double(0, 0); + + private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { + this.mw = mw; + this.mapMode = mapMode; + this.mapView = mapView; + } + + private void drawMap() { + + int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); + double tSize = (double) Config.textureSize; + double zoomScale = (double) (1 << regionZoomLevel); + + // if the texture UV coordinates do not line up with the texture pixels then the texture + // will look blurry when it is drawn to the screen. + // to fix this we round the texture coordinates to the nearest pixel boundary. + // this is unnecessary when zoomed in as the texture will be upscaled and look blurry + // anyway, so it is disabled in this case. + // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture + // pixel boundaries when zoomed in. + + double u, v, w, h; + if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; + v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; + w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; + h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; + } else { + double tSizeInBlocks = tSize * zoomScale; + u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; + v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; + w = (this.mapView.getWidth() / tSizeInBlocks); + h = (this.mapView.getHeight() / tSizeInBlocks); + } + + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + if (this.mapMode.config.circular) { + Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); + } + + if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { + // draw the underground map + this.mw.undergroundMapTexture.requestView(this.mapView); + // underground map needs to have a black background + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + this.mw.undergroundMapTexture.bind(); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } else { + // draw the surface map + MapViewRequest req = new MapViewRequest(this.mapView); + this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); + + // draw the background texture + if (Config.backgroundTextureMode > 0) { + double bu1 = 0.0; double bu2 = 1.0; + double bv1 = 0.0; double bv2 = 1.0; + if (Config.backgroundTextureMode == 2) { + // background moves with map if mode is 2 + double bSize = tSize / 256.0; + bu1 = u * bSize; bu2 = (u + w) * bSize; + bv1 = v * bSize; bv2 = (v + h) * bSize; + } + this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + bu1, bv1, bu2, bv2 + ); + } else { + // mode 0, no background texture + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + } + + // only draw surface map if the request is loaded (view requests are + // loaded by the background thread) + if (this.mw.mapTexture.isLoaded(req)) { + this.mw.mapTexture.bind(); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } + } + + // draw ProfMobius chunk overlay + IMwDataProvider provider = this.drawOverlay(); + + // overlay onDraw event + if (provider != null) { + GL11.glPushMatrix(); + provider.onDraw(this.mapView, this.mapMode); + GL11.glPopMatrix(); + } + + if (this.mapMode.config.circular) { + Render.disableStencil(); + } + + GL11.glPopMatrix(); + } + + private void drawBorder() { + if (this.mapMode.config.circular) { + this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); + } else { + this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); + } + Render.setColour(0xffffffff); + Render.drawTexturedRect( + this.mapMode.x / 0.75, this.mapMode.y / 0.75, + this.mapMode.w / 0.75, this.mapMode.h / 0.75, + 0.0, 0.0, 1.0, 1.0 + ); + } + + private void drawPlayerArrow() { + GL11.glPushMatrix(); + double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); + Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); + this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); + + // the arrow only needs to be rotated if the map is NOT rotated + GL11.glTranslated(p.x, p.y, 0.0); + if (!this.mapMode.config.rotate) { + GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); + Render.drawTexturedRect( + -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + GL11.glPopMatrix(); + } + + private void drawIcons() { + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + // draw markers + this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); + + // draw player trail + if (this.mw.playerTrail.enabled) { + this.mw.playerTrail.draw(this.mapMode, this.mapView); + } + + // draw north arrow + if (this.mapMode.config.rotate) { + double y = this.mapMode.h / 2.0; + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); + Render.drawTexturedRect( + -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + } + + GL11.glPopMatrix(); + + // outside of the matrix pop as theplayer arrow + // needs to be drawn without rotation + this.drawPlayerArrow(); + } + + private void drawCoords() { + // draw coordinates + if (this.mapMode.config.coordsEnabled) { + GL11.glPushMatrix(); + GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); + if (Config.coordsMode != Config.coordsModeStringArray[2]) { + GL11.glScalef(0.5f, 0.5f, 1.0f); + } + int offset = 0; + if (Config.coordsMode != Config.coordsModeStringArray[0]) { + Render.drawCentredString(0, 0, this.mapMode.textColour, + "%d, %d, %d", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt + ); + offset += 12; + } + if (Config.undergroundMode) { + Render.drawCentredString( + 0, offset, this.mapMode.textColour,"underground mode" + ); + } + GL11.glPopMatrix(); + } + } + + private IMwDataProvider drawOverlay() { + // draw overlays from registered providers + //for (IMwDataProvider provider : MwAPI.getDataProviders()) + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) { + ArrayList overlays = provider.getChunksOverlay( + this.mapView.getDimension(), + this.mapView.getX(), this.mapView.getZ(), + this.mapView.getMinX(), this.mapView.getMinZ(), + this.mapView.getMaxX(), this.mapView.getMaxZ() + ); + if (overlays != null) { + for (IMwChunkOverlay overlay : overlays) { + paintChunk(this.mapMode, this.mapView, overlay); + } + } + } + return provider; + } + + public void draw() { + + this.mapMode.setScreenRes(); + this.mapView.setMapWH(this.mapMode); + this.mapView.setTextureSize(Config.textureSize); + + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + + // translate to center of minimap + // z is -2000 so that it is drawn above the 3D world, but below GUI + // elements which are typically at -3000 + GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); + + // draw background, the map texture, and enabled overlays + this.drawMap(); + + if (this.mapMode.config.borderMode) { + this.drawBorder(); + } + this.drawIcons(); + + this.drawCoords(); + + // some shader mods seem to need depth testing re-enabled + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + + private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ + int chunkX = overlay.getCoordinates().x; + int chunkZ = overlay.getCoordinates().y; + float filling = overlay.getFilling(); + + Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); + Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); + + topCorner.x = Math.max(mapMode.x, topCorner.x); + topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); + topCorner.y = Math.max(mapMode.y, topCorner.y); + topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); + + botCorner.x = Math.max(mapMode.x, botCorner.x); + botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); + botCorner.y = Math.max(mapMode.y, botCorner.y); + botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); + + double sizeX = (botCorner.x - topCorner.x) * filling; + double sizeY = (botCorner.y - topCorner.y) * filling; + double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; + double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; + + if (overlay.hasBorder()) { + Render.setColour(overlay.getBorderColor()); + Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); + } + + Render.setColour(overlay.getColor()); + Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); + } + + public MapMode getMapMode() + { + return this.mapMode; + } +} + diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java index 14c7bbf3..0428d890 100644 --- a/src/main/java/mapwriter/map/MapView.java +++ b/src/main/java/mapwriter/map/MapView.java @@ -4,8 +4,8 @@ import mapwriter.Mw; import mapwriter.api.MwAPI; +import mapwriter.config.Config; import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Config; public class MapView { @@ -37,8 +37,8 @@ public class MapView { private boolean undergroundMode; public MapView(Mw mw) { - this.minZoom = Config.minZoom; - this.maxZoom = Config.maxZoom; + this.minZoom = Config.zoomInLevels; + this.maxZoom = Config.zoomOutLevels; this.undergroundMode = Config.undergroundMode; this.setZoomLevel(0); this.setViewCentre(mw.playerX, mw.playerZ); diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index 93feed2d..932968f0 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -1,85 +1,91 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.map.mapmode.LargeMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.map.mapmode.SmallMapMode; -import mapwriter.util.Config; -import mapwriter.util.Reference; - -public class MiniMap { - private Mw mw; - - public MapMode smallMapMode; - public MapMode largeMapMode; - public MapMode guiMapMode; - - public MapView view; - - public MapRenderer smallMap; - public MapRenderer largeMap; - - private List mapList; - private MapRenderer currentMap = null; - - public MiniMap(Mw mw) { - this.mw = mw; - - // map view shared between large and small map modes - this.view = new MapView(mw); - this.view.setZoomLevel(Config.zoomLevel); - - // small map mode - this.smallMapMode = new SmallMapMode(); - this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); - - // large map mode - this.largeMapMode = new LargeMapMode(); - this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); - - this.mapList = new ArrayList(); - - // add small, large and underground map modes if they - // are enabled. - if (this.smallMapMode.config.enabled) { - this.mapList.add(this.smallMap); - } - if (this.largeMapMode.config.enabled) { - this.mapList.add(this.largeMap); - } - // add a null entry (hides the overlay when selected) - this.mapList.add(null); - - // sanitize overlayModeIndex loaded from config - this.nextOverlayMode(0); - this.currentMap = this.mapList.get(Config.modeIndex); - } - - public void close() { - this.mapList.clear(); - this.currentMap = null; - } - - // toggle between small map, underground map and no map - public MapRenderer nextOverlayMode(int increment) { - int size = this.mapList.size(); - Config.modeIndex = (Config.modeIndex + size + increment) % size; - this.currentMap = this.mapList.get(Config.modeIndex); - return this.currentMap; - } - - public void toggleRotating() { - boolean rotate = this.smallMapMode.toggleRotating(); - this.largeMapMode.setRotating(rotate); - } - - // draw the map overlay, player arrow, and markers - public void drawCurrentMap() { - if (this.currentMap != null) { - this.currentMap.draw(); - } - } +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.config.Config; +import mapwriter.map.mapmode.LargeMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.map.mapmode.SmallMapMode; +import mapwriter.util.Reference; + +public class MiniMap { + private Mw mw; + + public MapMode smallMapMode; + public MapMode largeMapMode; + public MapMode guiMapMode; + + public MapView view; + + public MapRenderer smallMap; + public MapRenderer largeMap; + + private List mapList; + private MapRenderer currentMap = null; + + public MiniMap(Mw mw) { + this.mw = mw; + + // map view shared between large and small map modes + this.view = new MapView(mw); + this.view.setZoomLevel(Config.overlayZoomLevel); + + // small map mode + this.smallMapMode = new SmallMapMode(); + this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); + + // large map mode + this.largeMapMode = new LargeMapMode(); + this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); + + this.mapList = new ArrayList(); + + // add small, large and underground map modes if they + // are enabled. + if (this.smallMapMode.config.enabled) { + this.mapList.add(this.smallMap); + } + if (this.largeMapMode.config.enabled) { + this.mapList.add(this.largeMap); + } + // add a null entry (hides the overlay when selected) + this.mapList.add(null); + + // sanitize overlayModeIndex loaded from config + this.nextOverlayMode(0); + this.currentMap = this.mapList.get(Config.overlayModeIndex); + } + + public void close() { + this.mapList.clear(); + this.currentMap = null; + } + + // toggle between small map, underground map and no map + public MapRenderer nextOverlayMode(int increment) { + int size = this.mapList.size(); + Config.overlayModeIndex = (Config.overlayModeIndex + size + increment) % size; + + MapRenderer newMap = this.mapList.get(Config.overlayModeIndex); + + //if (newMap.getMapMode().config.enabled) + //{ + this.currentMap = newMap; + //} + return this.currentMap; + } + + public void toggleRotating() { + boolean rotate = this.smallMapMode.toggleRotating(); + this.largeMapMode.setRotating(rotate); + } + + // draw the map overlay, player arrow, and markers + public void drawCurrentMap() { + if (this.currentMap != null) { + this.currentMap.draw(); + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java index af42b224..ab82ace1 100644 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -1,11 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.util.Config; -import mapwriter.util.Reference; - - -public class FullScreenMapMode extends MapMode { - public FullScreenMapMode() { - super(Config.fullScreenMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; +import mapwriter.util.Reference; + + +public class FullScreenMapMode extends MapMode { + public FullScreenMapMode() { + super(Config.fullScreenMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java index 03a83b83..c78d5c43 100644 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -1,11 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.util.Config; -import mapwriter.util.Reference; - - -public class LargeMapMode extends MapMode { - public LargeMapMode() { - super(Config.largeMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; +import mapwriter.util.Reference; + + +public class LargeMapMode extends MapMode { + public LargeMapMode() { + super(Config.largeMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 37a943b1..0fc6e49a 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -1,208 +1,208 @@ -package mapwriter.map.mapmode; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.MapView; -import mapwriter.util.MapModeConfig; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class MapMode { - private int sw = 320; - private int sh = 240; - private double screenScalingFactor = 1.0; - - // calculated before every frame drawn by updateMapDimensions - public int xTranslation = 0; - public int yTranslation = 0; - public int x = -25; - public int y = -25; - public int w = 50; - public int h = 50; - public int wPixels = 50; - public int hPixels = 50; - - // config settings - - public int textX = 0; - public int textY = 0; - public int textColour = 0xffffffff; - - public MapModeConfig config; - - public MapMode(MapModeConfig config) { - this.config = config; - } - - public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { - if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { - this.sw = sw; - this.sh = sh; - this.screenScalingFactor = scaling; - this.update(); - } - } - - public void setScreenRes() { - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); - } - - public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { - this.config.marginTop = marginTop; - this.config.marginBottom = marginBottom; - this.config.marginLeft = marginLeft; - this.config.marginRight = marginRight; - this.update(); - } - - public void setHeightPercent(int heightPercent) { - this.config.heightPercent = heightPercent; - this.update(); - } - - public void toggleHeightPercent() { - int i = (this.config.heightPercent / 5) + 1; - if (i > 12) { - i = 1; - } - this.setHeightPercent(i * 5); - } - - private void update() { - int size = (this.sh * this.config.heightPercent) / 100; - int x, y; - - // calculate map x position and width - if ((this.config.marginLeft >= 0) && (this.config.marginRight >= 0)) { - x = this.config.marginLeft; - this.w = this.sw - this.config.marginLeft - this.config.marginRight; - } else if (this.config.marginLeft >= 0) { - x = this.config.marginLeft; - this.w = size; - } else if (this.config.marginRight >= 0) { - x = this.sw - size - this.config.marginRight; - this.w = size; - } else { - x = (this.sw - size) / 2; - this.w = size; - } - - // calculate map y position and height - if ((this.config.marginTop >= 0) && (this.config.marginBottom >= 0)) { - y = this.config.marginTop; - this.h = this.sh - this.config.marginTop - this.config.marginBottom; - } else if (this.config.marginTop >= 0) { - y = this.config.marginTop; - this.h = size; - } else if (this.config.marginBottom >= 0) { - y = this.sh - size - this.config.marginBottom; - this.h = size; - } else { - y = (this.sh - size) / 2; - this.h = size; - } - - // make sure width and height are multiples of 2 - this.w &= -2; - this.h &= -2; - - this.xTranslation = x + (this.w >> 1); - this.yTranslation = y + (this.h >> 1); - - if (this.config.circular) { - this.w = this.h; - } - - this.x = -(this.w >> 1); - this.y = -(this.h >> 1); - - this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); - this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); - - // calculate coords display location - this.textX = 0; - this.textY = (this.h >> 1) + 4; - - //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); - //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", - // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); - } - - public void setRotating(boolean enabled) { - this.config.rotate = enabled; - this.config.circular = enabled; - this.update(); - } - - public boolean toggleRotating() { - this.setRotating(!this.config.rotate); - return this.config.rotate; - } - - public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { - double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); - double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); - int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); - int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); - return new Point(bx, bz); - } - - public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { - double xNorm = (bX - mapView.getX()) / mapView.getWidth(); - double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); - return new Point.Double(this.w * xNorm, this.h * zNorm); - } - - public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { - double xRel = (bX - mapView.getX()) / mapView.getWidth(); - double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); - double limit = 0.49; - - if (!this.config.circular) { - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - if (zRel < -limit) { - xRel = -limit * xRel / zRel; - zRel = -limit; - } - if (zRel > limit) { - xRel = limit * xRel / zRel; - zRel = limit; - } - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - } else { - double dSq = (xRel * xRel) + (zRel * zRel); - if (dSq > (limit * limit)) { - double a = Math.atan2(zRel, xRel); - xRel = limit * Math.cos(a); - zRel = limit * Math.sin(a); - } - } - - // multiply by the overlay size and add the overlay position to - // get the position within the overlay in screen coordinates - return new Point.Double(this.w * xRel, this.h * zRel); - } -} +package mapwriter.map.mapmode; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.config.MapModeConfig; +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.MapView; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class MapMode { + private int sw = 320; + private int sh = 240; + private double screenScalingFactor = 1.0; + + // calculated before every frame drawn by updateMapDimensions + public int xTranslation = 0; + public int yTranslation = 0; + public int x = -25; + public int y = -25; + public int w = 50; + public int h = 50; + public int wPixels = 50; + public int hPixels = 50; + + // config settings + + public int textX = 0; + public int textY = 0; + public int textColour = 0xffffffff; + + public MapModeConfig config; + + public MapMode(MapModeConfig config) { + this.config = config; + } + + public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { + if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { + this.sw = sw; + this.sh = sh; + this.screenScalingFactor = scaling; + this.update(); + } + } + + public void setScreenRes() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); + } + + public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { + this.config.marginTop = marginTop; + this.config.marginBottom = marginBottom; + this.config.marginLeft = marginLeft; + this.config.marginRight = marginRight; + this.update(); + } + + public void setHeightPercent(int heightPercent) { + this.config.heightPercent = heightPercent; + this.update(); + } + + public void toggleHeightPercent() { + int i = (this.config.heightPercent / 5) + 1; + if (i > 12) { + i = 1; + } + this.setHeightPercent(i * 5); + } + + private void update() { + int size = (this.sh * this.config.heightPercent) / 100; + int x, y; + + // calculate map x position and width + if ((this.config.marginLeft >= 0) && (this.config.marginRight >= 0)) { + x = this.config.marginLeft; + this.w = this.sw - this.config.marginLeft - this.config.marginRight; + } else if (this.config.marginLeft >= 0) { + x = this.config.marginLeft; + this.w = size; + } else if (this.config.marginRight >= 0) { + x = this.sw - size - this.config.marginRight; + this.w = size; + } else { + x = (this.sw - size) / 2; + this.w = size; + } + + // calculate map y position and height + if ((this.config.marginTop >= 0) && (this.config.marginBottom >= 0)) { + y = this.config.marginTop; + this.h = this.sh - this.config.marginTop - this.config.marginBottom; + } else if (this.config.marginTop >= 0) { + y = this.config.marginTop; + this.h = size; + } else if (this.config.marginBottom >= 0) { + y = this.sh - size - this.config.marginBottom; + this.h = size; + } else { + y = (this.sh - size) / 2; + this.h = size; + } + + // make sure width and height are multiples of 2 + this.w &= -2; + this.h &= -2; + + this.xTranslation = x + (this.w >> 1); + this.yTranslation = y + (this.h >> 1); + + if (this.config.circular) { + this.w = this.h; + } + + this.x = -(this.w >> 1); + this.y = -(this.h >> 1); + + this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); + this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); + + // calculate coords display location + this.textX = 0; + this.textY = (this.h >> 1) + 4; + + //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); + //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", + // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); + } + + public void setRotating(boolean enabled) { + this.config.rotate = enabled; + this.config.circular = enabled; + this.update(); + } + + public boolean toggleRotating() { + this.setRotating(!this.config.rotate); + return this.config.rotate; + } + + public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { + double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); + double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); + int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); + int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); + return new Point(bx, bz); + } + + public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { + double xNorm = (bX - mapView.getX()) / mapView.getWidth(); + double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); + return new Point.Double(this.w * xNorm, this.h * zNorm); + } + + public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { + double xRel = (bX - mapView.getX()) / mapView.getWidth(); + double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); + double limit = 0.49; + + if (!this.config.circular) { + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + if (zRel < -limit) { + xRel = -limit * xRel / zRel; + zRel = -limit; + } + if (zRel > limit) { + xRel = limit * xRel / zRel; + zRel = limit; + } + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + } else { + double dSq = (xRel * xRel) + (zRel * zRel); + if (dSq > (limit * limit)) { + double a = Math.atan2(zRel, xRel); + xRel = limit * Math.cos(a); + zRel = limit * Math.sin(a); + } + } + + // multiply by the overlay size and add the overlay position to + // get the position within the overlay in screen coordinates + return new Point.Double(this.w * xRel, this.h * zRel); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java index 7d627434..13276515 100644 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -1,11 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.util.Config; -import mapwriter.util.Reference; - - -public class SmallMapMode extends MapMode { - public SmallMapMode() { - super(Config.smallMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; +import mapwriter.util.Reference; + + +public class SmallMapMode extends MapMode { + public SmallMapMode() { + super(Config.smallMap); + } +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 74b10b27..d3bdb2dc 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,22 +1,30 @@ -package mapwriter.util; - -import java.util.regex.Pattern; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public static final String catOptions = "options"; - public static final String catLargeMapConfig = "largemap"; - public static final String catSmallMapConfig = "smallmap"; - public static final String catFullMapConfig = "fullscreenmap"; - - public static final String PlayerTrailName = "player"; - - public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); -} +package mapwriter.util; + +import java.util.regex.Pattern; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public static final String catOptions = "options"; + public static final String catLargeMapConfig = "largemap"; + public static final String catSmallMapConfig = "smallmap"; + public static final String catFullMapConfig = "fullscreenmap"; + + public static final String PlayerTrailName = "player"; + + public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + + public static final String catWorld = "world"; + public static final String catMarkers = "markers"; + public static final String worldDirConfigName = "mapwriter.cfg"; + public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 14162e7a..7ad6680e 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -9,8 +9,11 @@ import java.util.Date; import java.util.List; +import mapwriter.Mw; +import mapwriter.config.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; @@ -107,4 +110,39 @@ public static int distToChunkSq(int x, int z, Chunk chunk) { int dz = (chunk.zPosition << 4) + 8 - z; return (dx * dx) + (dz * dz); } + + public static String getWorldName() { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + worldName = worldName.replace(":", "_"); + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } } diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index 3ad0e73d..b3a793dd 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -1,3 +1,4 @@ +# Keys key.mw_open_gui=Open map GUI key.mw_new_marker=New Waypoint key.mw_next_map_mode=Next map mode @@ -6,3 +7,77 @@ key.mw_teleport=Teleport to waypoint key.mw_zoom_in=Minimap zoom in key.mw_zoom_out=Minimap zoom out key.mw_underground_mode=Underground map mode + +#Config Global +mw.config.linearTextureScaling=Linear texture scaling enabled +mw.config.linearTextureScaling.tooltip=Enabled linear texture scaling. (nearest is used otherwise) +mw.config.useSavedBlockColours= Use saved block colors +mw.config.useSavedBlockColours.tooltip= +mw.config.teleportEnabled= Teleport enabled +mw.config.teleportEnabled.tooltip=Enables teleporting to positions on the map +mw.config.teleportCommand=Teleport Command +mw.config.teleportCommand.tooltip=The command used to teleport the player +mw.config.coordsMode= Coordinates mode +mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap +mw.config.maxChunkSaveDistSq=Max draw distance +mw.config.maxChunkSaveDistSq.tooltip=The square of the max distance from the player to map chunks at +mw.config.mapPixelSnapEnabled= Map pixel snap +mw.config.mapPixelSnapEnabled.tooltip= +mw.config.maxDeathMarkers=Max death markers +mw.config.maxDeathMarkers.tooltip=The maximum amount of death markers +mw.config.chunksPerTick=Chunks per tick +mw.config.chunksPerTick.tooltip=sets the maximum number of chunks updated per tick +mw.config.saveDirOverride=Save directory Override +mw.config.saveDirOverride.tooltip=Override the directory MapWriter uses to store images and region +mw.config.portNumberInWorldNameEnabled=Portnumber in world Name +mw.config.portNumberInWorldNameEnabled.tooltip=set to false to disable appending the port number to the world name for multiplayer worlds +mw.config.undergroundMode=Underground Mode +mw.config.undergroundMode.tooltip=Enables the underground mode +mw.config.regionFileOutputEnabledSP=Region file output SP +mw.config.regionFileOutputEnabledSP.tooltip=set to false to disable saving region files (mca files) in single player. prevents map regen if disabled +mw.config.regionFileOutputEnabledMP=Region file output MP +mw.config.regionFileOutputEnabledMP.tooltip=set to false to disable saving region files (mca files) in multiplayer. prevents map regen if disabled +mw.config.backgroundTextureMode= +mw.config.backgroundTextureMode.tooltip= +mw.config.zoomOutLevels=Zoom out levels +mw.config.zoomOutLevels.tooltip=Max number of steps you can zoom out. Larger values decrease performance. +mw.config.zoomInLevels=Zoom in levels +mw.config.zoomInLevels.tooltip=Max number of steps you can zoom in. Does not affect performance. +mw.config.textureSize= +mw.config.textureSize.tooltip= + +#Config Temp +mw.config.overlayModeIndex= +mw.config.overlayModeIndex.tooltip= +mw.config.overlayZoomLevel= +mw.config.overlayZoomLevel.tooltip= + +#Config map +mw.config.map.enabled=Map enabled +mw.config.map.enabled.tooltip=Set to false to disable this map view +mw.config.map.playerArrowSize=Player arrow Size +mw.config.map.playerArrowSize.tooltip=The size of the player arrow on the map +mw.config.map.markerSize=Marker size +mw.config.map.markerSize.tooltip=The size of markers on the map +mw.config.map.alphaPercent= Map opacity +mw.config.map.alphaPercent.tooltip=Map opacity. 0-100 percent +mw.config.map.heightPercent= +mw.config.map.heightPercent.tooltip=The map size as a percentage of the screen height. Ignored if both Left and Right or Bottom and Top margins are set. +mw.config.map.marginTop=Top margin +mw.config.map.marginTop.tooltip= +mw.config.map.marginBottom=Bottom margin +mw.config.map.marginBottom.tooltip= +mw.config.map.marginLeft=Left margin +mw.config.map.marginLeft.tooltip= +mw.config.map.marginRight=Right margin +mw.config.map.marginRight.tooltip= +mw.config.map.rotate=Rotate map +mw.config.map.rotate.tooltip=Set to true to rotate the map, only possible in circular mode +mw.config.map.circular=Circular map +mw.config.map.circular.tooltip=True = Circular map, false = square map +mw.config.map.coordsEnabled=Enable coordinates +mw.config.map.coordsEnabled.tooltip=set to true to display coordinates under map +mw.config.map.borderMode=Draw border +mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map +mw.config.map.trailMarkerSize=Trail marker size +mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map From 022c8242280ed9fc31647bd55a1b682f231ed06a Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 6 May 2015 16:46:01 +0200 Subject: [PATCH 031/109] Indenting --- src/main/java/mapwriter/ChunkManager.java | 302 ++--- src/main/java/mapwriter/Mw.java | 1036 ++++++++--------- src/main/java/mapwriter/config/Config.java | 121 +- .../handler/ConfigurationHandler.java | 247 ++-- src/main/java/mapwriter/map/MapRenderer.java | 650 +++++------ src/main/java/mapwriter/region/MwChunk.java | 784 ++++++------- src/main/java/mapwriter/util/Utils.java | 296 ++--- 7 files changed, 1717 insertions(+), 1719 deletions(-) diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index 4c7408d2..3e4cc446 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -1,152 +1,152 @@ -package mapwriter; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import mapwriter.config.Config; -import mapwriter.region.MwChunk; -import mapwriter.tasks.SaveChunkTask; -import mapwriter.tasks.UpdateSurfaceChunksTask; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.storage.ExtendedBlockStorage; - -public class ChunkManager { - public Mw mw; - private boolean closed = false; - private CircularHashMap chunkMap = new CircularHashMap(); - - private static final int VISIBLE_FLAG = 0x01; - private static final int VIEWED_FLAG = 0x02; - - public ChunkManager(Mw mw) { - this.mw = mw; - } - - public synchronized void close() { - this.closed = true; - this.saveChunks(); - this.chunkMap.clear(); - } - - // create MwChunk from Minecraft chunk. - // only MwChunk's should be used in the background thread. - // make this a full copy of chunk data to prevent possible race conditions <-- done - public static MwChunk copyToMwChunk(Chunk chunk) { - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = new HashMap(); - TileEntityMap.putAll(chunk.getTileEntityMap()); - char[][] dataArray = new char[16][]; - - ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); - if (storageArrays != null) { - for (ExtendedBlockStorage storage : storageArrays) { - if (storage != null) { - int y = (storage.getYLocation() >> 4) & 0xf; - dataArray[y] = storage.getData(); - lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; - } - } - } - - return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), - dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); - } - - public synchronized void addChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - this.chunkMap.put(chunk, 0); - } - } - - public synchronized void removeChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? - int flags = this.chunkMap.get(chunk); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(chunk); - } - this.chunkMap.remove(chunk); - } - } - - public synchronized void saveChunks() { - for (Map.Entry entry : this.chunkMap.entrySet()) { - int flags = entry.getValue(); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(entry.getKey()); - } - } - } - - public void updateUndergroundChunks() { - int chunkArrayX = (this.mw.playerXInt >> 4) - 1; - int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; - MwChunk[] chunkArray = new MwChunk[9]; - for (int z = 0; z < 3; z++) { - for (int x = 0; x < 3; x++) { - Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( - chunkArrayX + x, - chunkArrayZ + z - ); - if (!chunk.isEmpty()) { - chunkArray[(z * 3) + x] = copyToMwChunk(chunk); - } - } - } - } - - public void updateSurfaceChunks() { - int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); - MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; - for (int i = 0; i < chunksToUpdate; i++) { - Map.Entry entry = this.chunkMap.getNextEntry(); - if (entry != null) { - // if this chunk is within a certain distance to the player then - // add it to the viewed set - Chunk chunk = entry.getKey(); - - int flags = entry.getValue(); - if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { - flags |= (VISIBLE_FLAG | VIEWED_FLAG); - } else { - flags &= ~VISIBLE_FLAG; - } - entry.setValue(flags); - - if ((flags & VISIBLE_FLAG) != 0) { - chunkArray[i] = copyToMwChunk(chunk); - } else { - chunkArray[i] = null; - } - } - } - - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - public void onTick() { - if (!this.closed) { - if ((this.mw.tickCounter & 0xf) == 0) { - this.updateUndergroundChunks(); - } else { - this.updateSurfaceChunks(); - } - } - } - - public void forceChunks(MwChunk[] chunkArray){ - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - private void addSaveChunkTask(Chunk chunk) { - if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || - (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { - if (!chunk.isEmpty()) { - this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); - } - } - } +package mapwriter; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import mapwriter.config.Config; +import mapwriter.region.MwChunk; +import mapwriter.tasks.SaveChunkTask; +import mapwriter.tasks.UpdateSurfaceChunksTask; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +public class ChunkManager { + public Mw mw; + private boolean closed = false; + private CircularHashMap chunkMap = new CircularHashMap(); + + private static final int VISIBLE_FLAG = 0x01; + private static final int VIEWED_FLAG = 0x02; + + public ChunkManager(Mw mw) { + this.mw = mw; + } + + public synchronized void close() { + this.closed = true; + this.saveChunks(); + this.chunkMap.clear(); + } + + // create MwChunk from Minecraft chunk. + // only MwChunk's should be used in the background thread. + // make this a full copy of chunk data to prevent possible race conditions <-- done + public static MwChunk copyToMwChunk(Chunk chunk) { + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = new HashMap(); + TileEntityMap.putAll(chunk.getTileEntityMap()); + char[][] dataArray = new char[16][]; + + ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); + if (storageArrays != null) { + for (ExtendedBlockStorage storage : storageArrays) { + if (storage != null) { + int y = (storage.getYLocation() >> 4) & 0xf; + dataArray[y] = storage.getData(); + lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; + } + } + } + + return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), + dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); + } + + public synchronized void addChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + this.chunkMap.put(chunk, 0); + } + } + + public synchronized void removeChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? + int flags = this.chunkMap.get(chunk); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(chunk); + } + this.chunkMap.remove(chunk); + } + } + + public synchronized void saveChunks() { + for (Map.Entry entry : this.chunkMap.entrySet()) { + int flags = entry.getValue(); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(entry.getKey()); + } + } + } + + public void updateUndergroundChunks() { + int chunkArrayX = (this.mw.playerXInt >> 4) - 1; + int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; + MwChunk[] chunkArray = new MwChunk[9]; + for (int z = 0; z < 3; z++) { + for (int x = 0; x < 3; x++) { + Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( + chunkArrayX + x, + chunkArrayZ + z + ); + if (!chunk.isEmpty()) { + chunkArray[(z * 3) + x] = copyToMwChunk(chunk); + } + } + } + } + + public void updateSurfaceChunks() { + int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); + MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; + for (int i = 0; i < chunksToUpdate; i++) { + Map.Entry entry = this.chunkMap.getNextEntry(); + if (entry != null) { + // if this chunk is within a certain distance to the player then + // add it to the viewed set + Chunk chunk = entry.getKey(); + + int flags = entry.getValue(); + if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { + flags |= (VISIBLE_FLAG | VIEWED_FLAG); + } else { + flags &= ~VISIBLE_FLAG; + } + entry.setValue(flags); + + if ((flags & VISIBLE_FLAG) != 0) { + chunkArray[i] = copyToMwChunk(chunk); + } else { + chunkArray[i] = null; + } + } + } + + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + public void onTick() { + if (!this.closed) { + if ((this.mw.tickCounter & 0xf) == 0) { + this.updateUndergroundChunks(); + } else { + this.updateSurfaceChunks(); + } + } + } + + public void forceChunks(MwChunk[] chunkArray){ + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + private void addSaveChunkTask(Chunk chunk) { + if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || + (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { + if (!chunk.isEmpty()) { + this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + } + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index e1c1bcd9..2096d880 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -1,518 +1,518 @@ -package mapwriter; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; -import mapwriter.forge.MwForge; -import mapwriter.forge.MwKeyHandler; -import mapwriter.gui.MwGui; -import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.MapTexture; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.map.MiniMap; -import mapwriter.map.Trail; -import mapwriter.map.UndergroundTexture; -import mapwriter.overlay.OverlaySlime; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; -import mapwriter.tasks.CloseRegionManagerTask; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Render; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.config.Configuration; - -public class Mw { - public Minecraft mc = null; - - // directories - private final File configDir; - private final File saveDir; - public File worldDir = null; - public File imageDir = null; - - // flags and counters - public boolean ready = false; - //public boolean multiplayer = false; - public int tickCounter = 0; - - // player position and heading - public double playerX = 0.0; - public double playerZ = 0.0; - public double playerY = 0.0; - public int playerXInt = 0; - public int playerYInt = 0; - public int playerZInt = 0; - public double playerHeading = 0.0; - public int playerDimension = 0; - public double mapRotationDegrees = 0.0; - - // instances of components - public MapTexture mapTexture = null; - public UndergroundTexture undergroundMapTexture = null; - public BackgroundExecutor executor = null; - public MiniMap miniMap = null; - public MarkerManager markerManager = null; - public BlockColours blockColours = null; - public RegionManager regionManager = null; - public ChunkManager chunkManager = null; - public Trail playerTrail = null; - - private static Mw instance; - - public static Mw getInstance() { - if (instance == null ) { - synchronized (WorldConfig.class) { - if (instance == null) { - instance = new Mw(); - } - } - } - - return instance; - } - - private Mw() { - // client only initialization - this.mc = Minecraft.getMinecraft(); - - // create base save directory - this.saveDir = new File(this.mc.mcDataDir, "saves"); - this.configDir = new File(this.mc.mcDataDir, "config"); - - this.ready = false; - - RegionManager.logger = MwForge.logger; - - ConfigurationHandler.loadConfig(); - } - - public void setTextureSize() { - if (Config.configTextureSize != Config.textureSize) { - int maxTextureSize = Render.getMaxTextureSize(); - int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { - textureSize *= 2; - } - textureSize /= 2; - - Logging.log("GL reported max texture size = %d", maxTextureSize); - Logging.log("texture size from config = %d", Config.configTextureSize); - Logging.log("setting map texture size to = %d", textureSize); - - Config.textureSize = textureSize; - if (this.ready) { - // if we are already up and running need to close and reinitialize the map texture and - // region manager. - this.reloadMapTexture(); - } - } - } - - // update the saved player position and orientation - // called every tick - public void updatePlayer() { - // get player pos - this.playerX = (double) this.mc.thePlayer.posX; - this.playerY = (double) this.mc.thePlayer.posY; - this.playerZ = (double) this.mc.thePlayer.posZ; - this.playerXInt = (int) Math.floor(this.playerX); - this.playerYInt = (int) Math.floor(this.playerY); - this.playerZInt = (int) Math.floor(this.playerZ); - - // rotationYaw of 0 points due north, we want it to point due east instead - // so add pi/2 radians (90 degrees) - this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); - this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; - - // set by onWorldLoad - this.playerDimension = this.mc.theWorld.provider.getDimensionId(); - if (this.miniMap.view.getDimension() != this.playerDimension) - { - WorldConfig.getInstance().addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); - } - } - - public void toggleMarkerMode() { - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - } - - // cheap and lazy way to teleport... - public void teleportTo(int x, int y, int z) { - if (Config.teleportEnabled) { - this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void warpTo(String name) { - if (Config.teleportEnabled) { - //MwUtil.printBoth(String.format("warping to %s", name)); - this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); - } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!Config.teleportCommand.equals("warp")) { - double scale = mapView.getDimensionScaling(this.playerDimension); - this.teleportTo((int) (x / scale), y, (int) (z / scale)); - } else { - Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); - } - } - - public void teleportToMarker(Marker marker) { - if (Config.teleportCommand.equals("warp")) { - this.warpTo(marker.name); - } else if (marker.dimension == this.playerDimension) { - this.teleportTo(marker.x, marker.y, marker.z); - } else { - Utils.printBoth("cannot teleport to marker in different dimension"); - } - } - - public void loadBlockColourOverrides(BlockColours bc) { - File f = new File(this.configDir, Reference.blockColourOverridesFileName); - if (f.isFile()) { - Logging.logInfo("loading block colour overrides file %s", f); - bc.loadFromFile(f); - } else { - Logging.logInfo("recreating block colour overrides file %s", f); - BlockColours.writeOverridesFile(f); - if (f.isFile()) { - bc.loadFromFile(f); - } else { - Logging.logError("could not load block colour overrides from file %s", f); - } - } - } - - public void saveBlockColours(BlockColours bc) { - File f = new File(this.configDir, Reference.blockColourSaveFileName); - Logging.logInfo("saving block colours to '%s'", f); - bc.saveToFile(f); - } - - public void reloadBlockColours() { - BlockColours bc = new BlockColours(); - File f = new File(this.configDir, Reference.blockColourSaveFileName); - if (Config.useSavedBlockColours && f.isFile()) { - // load block colours from file - Logging.logInfo("loading block colours from %s", f); - bc.loadFromFile(f); - this.loadBlockColourOverrides(bc); - } else { - // generate block colours from current texture pack - Logging.logInfo("generating block colours"); - // block type overrides need to be loaded before the block colours are generated - this.loadBlockColourOverrides(bc); - BlockColourGen.genBlockColours(bc); - // load overrides again to override block and biome colours - this.loadBlockColourOverrides(bc); - this.saveBlockColours(bc); - } - this.blockColours = bc; - } - - public void reloadMapTexture() { - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.executor.close(); - MapTexture oldMapTexture = this.mapTexture; - MapTexture newMapTexture = new MapTexture(Config.textureSize, Config.linearTextureScaling); - this.mapTexture = newMapTexture; - if (oldMapTexture != null) { - oldMapTexture.close(); - } - this.executor = new BackgroundExecutor(); - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); - - UndergroundTexture oldTexture = this.undergroundMapTexture; - UndergroundTexture newTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScaling); - this.undergroundMapTexture = newTexture; - if (oldTexture != null) { - this.undergroundMapTexture.close(); - } - } - - public void toggleUndergroundMode() { - Config.undergroundMode = !Config.undergroundMode; - this.miniMap.view.setUndergroundMode(Config.undergroundMode); - } - - //////////////////////////////// - // Initialization and Cleanup - //////////////////////////////// - - public void load() { - - if (this.ready) { - return; - } - - if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { - Logging.log("Mw.load: world or player is null, cannot load yet"); - return; - } - - Logging.log("Mw.load: loading..."); - - // get world and image directories - File saveDir = this.saveDir; - if (Config.saveDirOverride.length() > 0) { - File d = new File(Config.saveDirOverride); - if (d.isDirectory()) { - saveDir = d; - } else { - Logging.log("error: no such directory %s", Config.saveDirOverride); - } - } - - if (this.mc.isSingleplayer()) { - this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), Utils.getWorldName()); - } else { - this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), Utils.getWorldName()); - } - - // create directories - this.imageDir = new File(this.worldDir, "images"); - if (!this.imageDir.exists()) { - this.imageDir.mkdirs(); - } - if (!this.imageDir.isDirectory()) { - Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); - } - - this.tickCounter = 0; - - //this.multiplayer = !this.mc.isIntegratedServerRunning(); - - // marker manager only depends on the config being loaded - this.markerManager = new MarkerManager(); - this.markerManager.load(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); - - this.playerTrail = new Trail(this, Reference.PlayerTrailName); - - // executor does not depend on anything - this.executor = new BackgroundExecutor(); - - // mapTexture depends on config being loaded - this.mapTexture = new MapTexture(Config.textureSize, Config.linearTextureScaling); - this.undergroundMapTexture = new UndergroundTexture(this, Config.textureSize, Config.linearTextureScaling); - this.reloadBlockColours(); - // region manager depends on config, mapTexture, and block colours - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); - // overlay manager depends on mapTexture - this.miniMap = new MiniMap(this); - this.miniMap.view.setDimension(this.mc.thePlayer.dimension); - - this.chunkManager = new ChunkManager(this); - - this.ready = true; - - //if (!zoomLevelsExist) { - //printBoth("recreating zoom levels"); - //this.regionManager.recreateAllZoomLevels(); - //} - } - - public void close() { - - Logging.log("Mw.close: closing..."); - - if (this.ready) { - this.ready = false; - - this.chunkManager.close(); - this.chunkManager = null; - - // close all loaded regions, saving modified images. - // this will create extra tasks that need to be completed. - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.regionManager = null; - - Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); - if (this.executor.close()) { - Logging.log("error: timeout waiting for tasks to finish"); - } - Logging.log("done"); - - this.playerTrail.close(); - - this.markerManager.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); - this.markerManager.clear(); - - // close overlay - this.miniMap.close(); - this.miniMap = null; - - this.undergroundMapTexture.close(); - this.mapTexture.close(); - - WorldConfig.getInstance().saveWorldConfig(); - //this.saveConfig(); - - this.tickCounter = 0; - - OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in - } - } - - //////////////////////////////// - // Event handlers - //////////////////////////////// - - public void onTick() { - this.load(); - if (this.ready && (this.mc.thePlayer != null)) { - - this.updatePlayer(); - - if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { - this.undergroundMapTexture.update(); - } - - if (!(this.mc.currentScreen instanceof MwGui)) { - // if in game (no gui screen) center the minimap on the player and render it. - this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); - this.miniMap.drawCurrentMap(); - } - - // process background tasks - int maxTasks = 50; - while (!this.executor.processTaskQueue() && (maxTasks > 0)) { - maxTasks--; - } - - this.chunkManager.onTick(); - - // update GL texture of mapTexture if updated - this.mapTexture.processTextureUpdates(); - - // let the renderEngine know we have changed the bound texture. - //this.mc.renderEngine.resetBoundTexture(); - - //if (this.tickCounter % 100 == 0) { - // MwUtil.log("tick %d", this.tickCounter); - //} - this.playerTrail.onTick(); - - this.tickCounter++; - } - } - - // add chunk to the set of loaded chunks - public void onChunkLoad(Chunk chunk) { - this.load(); - if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - if (this.ready) { - this.chunkManager.addChunk(chunk); - } else { - Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); - } - } - } - - // remove chunk from the set of loaded chunks. - // convert to mwchunk and write chunk to region file if in multiplayer. - public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - this.chunkManager.removeChunk(chunk); - } - } - - // from onTick when mc.currentScreen is an instance of GuiGameOver - // it's the only option to detect death client side - public void onPlayerDeath(EntityPlayerMP player) { - if (this.ready && (Config.maxDeathMarkers > 0)) { - this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; - for (int i = 0; i < deleteCount; i++) { - // delete the first marker found in the group "playerDeaths". - // as new markers are only ever appended to the marker list this will delete the - // earliest death marker added. - this.markerManager.delMarker(null, "playerDeaths"); - } - - this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); - this.markerManager.setVisibleGroupName("playerDeaths"); - this.markerManager.update(); - } - } - - public void onKeyDown(KeyBinding kb) { - // make sure not in GUI element (e.g. chat box) - if ((this.mc.currentScreen == null) && (this.ready)) { - //Mw.log("client tick: %s key pressed", kb.keyDescription); - - if (kb == MwKeyHandler.keyMapMode) { - // map mode toggle - this.miniMap.nextOverlayMode(1); - - } else if (kb == MwKeyHandler.keyMapGui) { - // open map gui - this.mc.displayGuiScreen(new MwGui(this)); - - } else if (kb == MwKeyHandler.keyNewMarker) { - // open new marker dialog - String group = this.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - - } else if (kb == MwKeyHandler.keyNextGroup) { - // toggle marker mode - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - - } else if (kb == MwKeyHandler.keyTeleport) { - // set or remove marker - Marker marker = this.markerManager.getNearestMarkerInDirection( - this.playerXInt, - this.playerZInt, - this.playerHeading); - if (marker != null) { - this.teleportToMarker(marker); - } - } else if (kb == MwKeyHandler.keyZoomIn) { - // zoom in - this.miniMap.view.adjustZoomLevel(-1); - } else if (kb == MwKeyHandler.keyZoomOut) { - // zoom out - this.miniMap.view.adjustZoomLevel(1); - } else if (kb == MwKeyHandler.keyUndergroundMode) { - this.toggleUndergroundMode(); - } - } - } -} +package mapwriter; + +import java.io.File; + +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwForge; +import mapwriter.forge.MwKeyHandler; +import mapwriter.gui.MwGui; +import mapwriter.gui.MwGuiMarkerDialog; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.map.MapTexture; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.map.MiniMap; +import mapwriter.map.Trail; +import mapwriter.map.UndergroundTexture; +import mapwriter.overlay.OverlaySlime; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; +import mapwriter.tasks.CloseRegionManagerTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Render; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Mw { + public Minecraft mc = null; + + // directories + private final File configDir; + private final File saveDir; + public File worldDir = null; + public File imageDir = null; + + // flags and counters + public boolean ready = false; + //public boolean multiplayer = false; + public int tickCounter = 0; + + public int textureSize = 2048; + + // player position and heading + public double playerX = 0.0; + public double playerZ = 0.0; + public double playerY = 0.0; + public int playerXInt = 0; + public int playerYInt = 0; + public int playerZInt = 0; + public double playerHeading = 0.0; + public int playerDimension = 0; + public double mapRotationDegrees = 0.0; + + // instances of components + public MapTexture mapTexture = null; + public UndergroundTexture undergroundMapTexture = null; + public BackgroundExecutor executor = null; + public MiniMap miniMap = null; + public MarkerManager markerManager = null; + public BlockColours blockColours = null; + public RegionManager regionManager = null; + public ChunkManager chunkManager = null; + public Trail playerTrail = null; + + private static Mw instance; + + public static Mw getInstance() { + if (instance == null ) { + synchronized (WorldConfig.class) { + if (instance == null) { + instance = new Mw(); + } + } + } + + return instance; + } + + private Mw() { + // client only initialization + this.mc = Minecraft.getMinecraft(); + + // create base save directory + this.saveDir = new File(this.mc.mcDataDir, "saves"); + this.configDir = new File(this.mc.mcDataDir, "config"); + + this.ready = false; + + RegionManager.logger = MwForge.logger; + + ConfigurationHandler.loadConfig(); + } + + public void setTextureSize() { + if (Config.configTextureSize != this.textureSize) { + int maxTextureSize = Render.getMaxTextureSize(); + int textureSize = 1024; + while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { + textureSize *= 2; + } + textureSize /= 2; + + Logging.log("GL reported max texture size = %d", maxTextureSize); + Logging.log("texture size from config = %d", Config.configTextureSize); + Logging.log("setting map texture size to = %d", textureSize); + + this.textureSize = textureSize; + if (this.ready) { + // if we are already up and running need to close and reinitialize the map texture and + // region manager. + this.reloadMapTexture(); + } + } + } + + // update the saved player position and orientation + // called every tick + public void updatePlayer() { + // get player pos + this.playerX = (double) this.mc.thePlayer.posX; + this.playerY = (double) this.mc.thePlayer.posY; + this.playerZ = (double) this.mc.thePlayer.posZ; + this.playerXInt = (int) Math.floor(this.playerX); + this.playerYInt = (int) Math.floor(this.playerY); + this.playerZInt = (int) Math.floor(this.playerZ); + + // rotationYaw of 0 points due north, we want it to point due east instead + // so add pi/2 radians (90 degrees) + this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); + this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; + + // set by onWorldLoad + this.playerDimension = this.mc.theWorld.provider.getDimensionId(); + if (this.miniMap.view.getDimension() != this.playerDimension) + { + WorldConfig.getInstance().addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); + } + } + + public void toggleMarkerMode() { + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + } + + // cheap and lazy way to teleport... + public void teleportTo(int x, int y, int z) { + if (Config.teleportEnabled) { + this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void warpTo(String name) { + if (Config.teleportEnabled) { + //MwUtil.printBoth(String.format("warping to %s", name)); + this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); + } else { + Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void teleportToMapPos(MapView mapView, int x, int y, int z) { + if (!Config.teleportCommand.equals("warp")) { + double scale = mapView.getDimensionScaling(this.playerDimension); + this.teleportTo((int) (x / scale), y, (int) (z / scale)); + } else { + Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); + } + } + + public void teleportToMarker(Marker marker) { + if (Config.teleportCommand.equals("warp")) { + this.warpTo(marker.name); + } else if (marker.dimension == this.playerDimension) { + this.teleportTo(marker.x, marker.y, marker.z); + } else { + Utils.printBoth("cannot teleport to marker in different dimension"); + } + } + + public void loadBlockColourOverrides(BlockColours bc) { + File f = new File(this.configDir, Reference.blockColourOverridesFileName); + if (f.isFile()) { + Logging.logInfo("loading block colour overrides file %s", f); + bc.loadFromFile(f); + } else { + Logging.logInfo("recreating block colour overrides file %s", f); + BlockColours.writeOverridesFile(f); + if (f.isFile()) { + bc.loadFromFile(f); + } else { + Logging.logError("could not load block colour overrides from file %s", f); + } + } + } + + public void saveBlockColours(BlockColours bc) { + File f = new File(this.configDir, Reference.blockColourSaveFileName); + Logging.logInfo("saving block colours to '%s'", f); + bc.saveToFile(f); + } + + public void reloadBlockColours() { + BlockColours bc = new BlockColours(); + File f = new File(this.configDir, Reference.blockColourSaveFileName); + if (Config.useSavedBlockColours && f.isFile()) { + // load block colours from file + Logging.logInfo("loading block colours from %s", f); + bc.loadFromFile(f); + this.loadBlockColourOverrides(bc); + } else { + // generate block colours from current texture pack + Logging.logInfo("generating block colours"); + // block type overrides need to be loaded before the block colours are generated + this.loadBlockColourOverrides(bc); + BlockColourGen.genBlockColours(bc); + // load overrides again to override block and biome colours + this.loadBlockColourOverrides(bc); + this.saveBlockColours(bc); + } + this.blockColours = bc; + } + + public void reloadMapTexture() { + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.executor.close(); + MapTexture oldMapTexture = this.mapTexture; + MapTexture newMapTexture = new MapTexture(this.textureSize, Config.linearTextureScaling); + this.mapTexture = newMapTexture; + if (oldMapTexture != null) { + oldMapTexture.close(); + } + this.executor = new BackgroundExecutor(); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); + + UndergroundTexture oldTexture = this.undergroundMapTexture; + UndergroundTexture newTexture = new UndergroundTexture(this, this.textureSize, Config.linearTextureScaling); + this.undergroundMapTexture = newTexture; + if (oldTexture != null) { + this.undergroundMapTexture.close(); + } + } + + public void toggleUndergroundMode() { + Config.undergroundMode = !Config.undergroundMode; + this.miniMap.view.setUndergroundMode(Config.undergroundMode); + } + + //////////////////////////////// + // Initialization and Cleanup + //////////////////////////////// + + public void load() { + + if (this.ready) { + return; + } + + if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { + Logging.log("Mw.load: world or player is null, cannot load yet"); + return; + } + + Logging.log("Mw.load: loading..."); + + // get world and image directories + File saveDir = this.saveDir; + if (Config.saveDirOverride.length() > 0) { + File d = new File(Config.saveDirOverride); + if (d.isDirectory()) { + saveDir = d; + } else { + Logging.log("error: no such directory %s", Config.saveDirOverride); + } + } + + if (this.mc.isSingleplayer()) { + this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), Utils.getWorldName()); + } else { + this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), Utils.getWorldName()); + } + + // create directories + this.imageDir = new File(this.worldDir, "images"); + if (!this.imageDir.exists()) { + this.imageDir.mkdirs(); + } + if (!this.imageDir.isDirectory()) { + Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); + } + + this.tickCounter = 0; + + //this.multiplayer = !this.mc.isIntegratedServerRunning(); + + // marker manager only depends on the config being loaded + this.markerManager = new MarkerManager(); + this.markerManager.load(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); + + this.playerTrail = new Trail(this, Reference.PlayerTrailName); + + // executor does not depend on anything + this.executor = new BackgroundExecutor(); + + // mapTexture depends on config being loaded + this.mapTexture = new MapTexture(this.textureSize, Config.linearTextureScaling); + this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, Config.linearTextureScaling); + this.reloadBlockColours(); + // region manager depends on config, mapTexture, and block colours + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); + // overlay manager depends on mapTexture + this.miniMap = new MiniMap(this); + this.miniMap.view.setDimension(this.mc.thePlayer.dimension); + + this.chunkManager = new ChunkManager(this); + + this.ready = true; + + //if (!zoomLevelsExist) { + //printBoth("recreating zoom levels"); + //this.regionManager.recreateAllZoomLevels(); + //} + } + + public void close() { + + Logging.log("Mw.close: closing..."); + + if (this.ready) { + this.ready = false; + + this.chunkManager.close(); + this.chunkManager = null; + + // close all loaded regions, saving modified images. + // this will create extra tasks that need to be completed. + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.regionManager = null; + + Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); + if (this.executor.close()) { + Logging.log("error: timeout waiting for tasks to finish"); + } + Logging.log("done"); + + this.playerTrail.close(); + + this.markerManager.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); + this.markerManager.clear(); + + // close overlay + this.miniMap.close(); + this.miniMap = null; + + this.undergroundMapTexture.close(); + this.mapTexture.close(); + + WorldConfig.getInstance().saveWorldConfig(); + //this.saveConfig(); + + this.tickCounter = 0; + + OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in + } + } + + //////////////////////////////// + // Event handlers + //////////////////////////////// + + public void onTick() { + this.load(); + if (this.ready && (this.mc.thePlayer != null)) { + + setTextureSize(); + + this.updatePlayer(); + + if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { + this.undergroundMapTexture.update(); + } + + if (!(this.mc.currentScreen instanceof MwGui)) { + // if in game (no gui screen) center the minimap on the player and render it. + this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); + this.miniMap.drawCurrentMap(); + } + + // process background tasks + int maxTasks = 50; + while (!this.executor.processTaskQueue() && (maxTasks > 0)) { + maxTasks--; + } + + this.chunkManager.onTick(); + + // update GL texture of mapTexture if updated + this.mapTexture.processTextureUpdates(); + + // let the renderEngine know we have changed the bound texture. + //this.mc.renderEngine.resetBoundTexture(); + + //if (this.tickCounter % 100 == 0) { + // MwUtil.log("tick %d", this.tickCounter); + //} + this.playerTrail.onTick(); + + this.tickCounter++; + } + } + + // add chunk to the set of loaded chunks + public void onChunkLoad(Chunk chunk) { + this.load(); + if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + if (this.ready) { + this.chunkManager.addChunk(chunk); + } else { + Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); + } + } + } + + // remove chunk from the set of loaded chunks. + // convert to mwchunk and write chunk to region file if in multiplayer. + public void onChunkUnload(Chunk chunk) { + if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + this.chunkManager.removeChunk(chunk); + } + } + + // from onTick when mc.currentScreen is an instance of GuiGameOver + // it's the only option to detect death client side + public void onPlayerDeath(EntityPlayerMP player) { + if (this.ready && (Config.maxDeathMarkers > 0)) { + this.updatePlayer(); + int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; + for (int i = 0; i < deleteCount; i++) { + // delete the first marker found in the group "playerDeaths". + // as new markers are only ever appended to the marker list this will delete the + // earliest death marker added. + this.markerManager.delMarker(null, "playerDeaths"); + } + + this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); + this.markerManager.setVisibleGroupName("playerDeaths"); + this.markerManager.update(); + } + } + + public void onKeyDown(KeyBinding kb) { + // make sure not in GUI element (e.g. chat box) + if ((this.mc.currentScreen == null) && (this.ready)) { + //Mw.log("client tick: %s key pressed", kb.keyDescription); + + if (kb == MwKeyHandler.keyMapMode) { + // map mode toggle + this.miniMap.nextOverlayMode(1); + + } else if (kb == MwKeyHandler.keyMapGui) { + // open map gui + this.mc.displayGuiScreen(new MwGui(this)); + + } else if (kb == MwKeyHandler.keyNewMarker) { + // open new marker dialog + String group = this.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + null, + this.markerManager, + "", + group, + this.playerXInt, + this.playerYInt, + this.playerZInt, + this.playerDimension + ) + ); + + } else if (kb == MwKeyHandler.keyNextGroup) { + // toggle marker mode + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + + } else if (kb == MwKeyHandler.keyTeleport) { + // set or remove marker + Marker marker = this.markerManager.getNearestMarkerInDirection( + this.playerXInt, + this.playerZInt, + this.playerHeading); + if (marker != null) { + this.teleportToMarker(marker); + } + } else if (kb == MwKeyHandler.keyZoomIn) { + // zoom in + this.miniMap.view.adjustZoomLevel(-1); + } else if (kb == MwKeyHandler.keyZoomOut) { + // zoom out + this.miniMap.view.adjustZoomLevel(1); + } else if (kb == MwKeyHandler.keyUndergroundMode) { + this.toggleUndergroundMode(); + } + } + } +} diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index f750bbd0..4ee8b16e 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -1,61 +1,60 @@ -package mapwriter.config; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.util.Reference; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class Config { - public static final String[] miniMapPositionStringArray = { - "unchanged", - "top right", - "top left", - "bottom right", - "bottom left" - }; - public static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; - public static final String[] backgroundModeStringArray = { - "none", - "static", - "panning" - }; - - // configuration options - public static boolean linearTextureScaling = true; - public static String coordsMode = coordsModeStringArray[0]; - public static boolean undergroundMode = false; - public static boolean teleportEnabled = true; - public static String teleportCommand = "tp"; - public static int defaultTeleportHeight = 80; - public static int zoomOutLevels = 5; - public static int zoomInLevels = -5; - public static boolean useSavedBlockColours = false; - public static int maxChunkSaveDistSq = 128 * 128; - public static boolean mapPixelSnapEnabled = true; - public static int textureSize = 2048; - public static int configTextureSize = 2048; - public static int maxDeathMarkers = 3; - public static int chunksPerTick = 5; - public static boolean portNumberInWorldNameEnabled = true; - public static String saveDirOverride = ""; - public static boolean regionFileOutputEnabledSP = true; - public static boolean regionFileOutputEnabledMP = true; - public static int backgroundTextureMode = 0; - - //World configuration Options - public static int overlayModeIndex = 0; - public static int overlayZoomLevel = 0; - - public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); - public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); - public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); -} +package mapwriter.config; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.handler.ConfigurationHandler; +import mapwriter.util.Reference; +import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class Config { + public static final String[] miniMapPositionStringArray = { + "unchanged", + "top right", + "top left", + "bottom right", + "bottom left" + }; + public static final String[] coordsModeStringArray = { + "disabled", + "small", + "large" + }; + public static final String[] backgroundModeStringArray = { + "none", + "static", + "panning" + }; + + // configuration options + public static boolean linearTextureScaling = true; + public static String coordsMode = coordsModeStringArray[0]; + public static boolean undergroundMode = false; + public static boolean teleportEnabled = true; + public static String teleportCommand = "tp"; + public static int defaultTeleportHeight = 80; + public static int zoomOutLevels = 5; + public static int zoomInLevels = -5; + public static boolean useSavedBlockColours = false; + public static int maxChunkSaveDistSq = 128 * 128; + public static boolean mapPixelSnapEnabled = true; + public static int configTextureSize = 2048; + public static int maxDeathMarkers = 3; + public static int chunksPerTick = 5; + public static boolean portNumberInWorldNameEnabled = true; + public static String saveDirOverride = ""; + public static boolean regionFileOutputEnabledSP = true; + public static boolean regionFileOutputEnabledMP = true; + public static int backgroundTextureMode = 0; + + //World configuration Options + public static int overlayModeIndex = 0; + public static int overlayZoomLevel = 0; + + public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); + public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); + public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); +} diff --git a/src/main/java/mapwriter/handler/ConfigurationHandler.java b/src/main/java/mapwriter/handler/ConfigurationHandler.java index 0a67b082..dd50254a 100644 --- a/src/main/java/mapwriter/handler/ConfigurationHandler.java +++ b/src/main/java/mapwriter/handler/ConfigurationHandler.java @@ -1,125 +1,124 @@ -package mapwriter.handler; - -import java.io.File; - -import mapwriter.Mw; -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.fml.client.event.ConfigChangedEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - - public class ConfigurationHandler - { - // configuration files (global and world specific) - public static Configuration configuration; - - public static void init(File configFile) - { - // Create the configuration object from the given configuration file - if (configuration == null) - { - configuration = new Configuration(configFile); - setMapModeDefaults(); - loadConfig(); - } - } - - public static void loadConfig() - { - Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScaling, "mw.config.linearTextureScaling"); - Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, "mw.config.useSavedBlockColours"); - Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, "mw.config.teleportEnabled"); - Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, "mw.config.teleportCommand"); - Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "mw.config.coordsMode", Config.coordsModeStringArray); - Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); - Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, "mw.config.mapPixelSnapEnabled"); - Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, "mw.config.maxDeathMarkers"); - Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, "mw.config.chunksPerTick"); - Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, "mw.config.saveDirOverride"); - Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, "mw.config.portNumberInWorldNameEnabled"); - Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, "mw.config.undergroundMode"); - Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, "mw.config.regionFileOutputEnabledSP"); - Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, "mw.config.backgroundTextureMode"); - - Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevels, 1, 256, "mw.config.zoomOutLevels"); - Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevels, 1, 256, "mw.config.zoomInLevels"); - - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, "mw.config.textureSize"); - - Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndex, 0, 1000, "mw.config.overlayModeIndex"); - Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); - - Config.fullScreenMap.loadConfig(); - Config.largeMap.loadConfig(); - Config.smallMap.loadConfig(); - - if (configuration.hasChanged()) - { - configuration.save(); - //Mw.getInstance().setTextureSize(); - } - } - - - @SubscribeEvent - public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) - { - if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) - { - loadConfig(); - } - } - - public static void setMapModeDefaults() - { - Config.fullScreenMap.heightPercent = -1; - Config.fullScreenMap.marginTop = 0; - Config.fullScreenMap.marginBottom = 0; - Config.fullScreenMap.marginLeft = 0; - Config.fullScreenMap.marginRight = 0; - Config.fullScreenMap.borderMode = false; - Config.fullScreenMap.playerArrowSize = 5; - Config.fullScreenMap.markerSize = 5; - Config.fullScreenMap.alphaPercent = 100; - Config.fullScreenMap.rotate = false; - Config.fullScreenMap.circular = false; - Config.fullScreenMap.coordsEnabled = false; - - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "enabled", Config.fullScreenMap.enabled).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); - - Config.largeMap.heightPercent = -1; - Config.largeMap.marginTop = 10; - Config.largeMap.marginBottom = 40; - Config.largeMap.marginLeft = 40; - Config.largeMap.marginRight = 40; - Config.largeMap.playerArrowSize = 5; - Config.largeMap.markerSize = 5; - Config.largeMap.coordsEnabled = true; - - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", Config.largeMap.enabled).setRequiresWorldRestart(true); - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); - - Config.smallMap.heightPercent = 30; - Config.smallMap.marginTop = 10; - Config.smallMap.marginBottom = -1; - Config.smallMap.marginLeft = -1; - Config.smallMap.marginRight = 10; - Config.smallMap.playerArrowSize = 4; - Config.smallMap.markerSize = 3; - Config.smallMap.coordsEnabled = true; - - ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", Config.smallMap.enabled).setRequiresWorldRestart(true); - } +package mapwriter.handler; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.fml.client.event.ConfigChangedEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + + public class ConfigurationHandler + { + // configuration files (global and world specific) + public static Configuration configuration; + + public static void init(File configFile) + { + // Create the configuration object from the given configuration file + if (configuration == null) + { + configuration = new Configuration(configFile); + setMapModeDefaults(); + loadConfig(); + } + } + + public static void loadConfig() + { + Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScaling, "mw.config.linearTextureScaling"); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, "mw.config.useSavedBlockColours"); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, "mw.config.teleportEnabled"); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, "mw.config.teleportCommand"); + Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "mw.config.coordsMode", Config.coordsModeStringArray); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, "mw.config.mapPixelSnapEnabled"); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, "mw.config.maxDeathMarkers"); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, "mw.config.chunksPerTick"); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, "mw.config.saveDirOverride"); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, "mw.config.portNumberInWorldNameEnabled"); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, "mw.config.undergroundMode"); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, "mw.config.regionFileOutputEnabledSP"); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, "mw.config.regionFileOutputEnabledMP"); + Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, "mw.config.backgroundTextureMode"); + + Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevels, 1, 256, "mw.config.zoomOutLevels"); + Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevels, 1, 256, "mw.config.zoomInLevels"); + + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, "mw.config.textureSize"); + + Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndex, 0, 1000, "mw.config.overlayModeIndex"); + Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); + + Config.fullScreenMap.loadConfig(); + Config.largeMap.loadConfig(); + Config.smallMap.loadConfig(); + + if (configuration.hasChanged()) + { + configuration.save(); + } + } + + + @SubscribeEvent + public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) + { + if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) + { + loadConfig(); + } + } + + public static void setMapModeDefaults() + { + Config.fullScreenMap.heightPercent = -1; + Config.fullScreenMap.marginTop = 0; + Config.fullScreenMap.marginBottom = 0; + Config.fullScreenMap.marginLeft = 0; + Config.fullScreenMap.marginRight = 0; + Config.fullScreenMap.borderMode = false; + Config.fullScreenMap.playerArrowSize = 5; + Config.fullScreenMap.markerSize = 5; + Config.fullScreenMap.alphaPercent = 100; + Config.fullScreenMap.rotate = false; + Config.fullScreenMap.circular = false; + Config.fullScreenMap.coordsEnabled = false; + + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "enabled", Config.fullScreenMap.enabled).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); + + Config.largeMap.heightPercent = -1; + Config.largeMap.marginTop = 10; + Config.largeMap.marginBottom = 40; + Config.largeMap.marginLeft = 40; + Config.largeMap.marginRight = 40; + Config.largeMap.playerArrowSize = 5; + Config.largeMap.markerSize = 5; + Config.largeMap.coordsEnabled = true; + + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", Config.largeMap.enabled).setRequiresWorldRestart(true); + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); + + Config.smallMap.heightPercent = 30; + Config.smallMap.marginTop = 10; + Config.smallMap.marginBottom = -1; + Config.smallMap.marginLeft = -1; + Config.smallMap.marginRight = 10; + Config.smallMap.playerArrowSize = 4; + Config.smallMap.markerSize = 3; + Config.smallMap.coordsEnabled = true; + + ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", Config.smallMap.enabled).setRequiresWorldRestart(true); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 6a12ac19..5dfe420f 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -1,325 +1,325 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.Mw; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.config.Config; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Render; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -public class MapRenderer { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - // accessed by the MwGui to check whether the mouse cursor is near the - // player arrow on the rendered map - public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { - this.mw = mw; - this.mapMode = mapMode; - this.mapView = mapView; - } - - private void drawMap() { - - int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) Config.textureSize; - double zoomScale = (double) (1 << regionZoomLevel); - - // if the texture UV coordinates do not line up with the texture pixels then the texture - // will look blurry when it is drawn to the screen. - // to fix this we round the texture coordinates to the nearest pixel boundary. - // this is unnecessary when zoomed in as the texture will be upscaled and look blurry - // anyway, so it is disabled in this case. - // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture - // pixel boundaries when zoomed in. - - double u, v, w, h; - if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { - u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; - v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; - w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; - h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; - } else { - double tSizeInBlocks = tSize * zoomScale; - u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; - v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; - w = (this.mapView.getWidth() / tSizeInBlocks); - h = (this.mapView.getHeight() / tSizeInBlocks); - } - - GL11.glPushMatrix(); - - if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - if (this.mapMode.config.circular) { - Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); - } - - if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { - // draw the underground map - this.mw.undergroundMapTexture.requestView(this.mapView); - // underground map needs to have a black background - Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - this.mw.undergroundMapTexture.bind(); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } else { - // draw the surface map - MapViewRequest req = new MapViewRequest(this.mapView); - this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); - - // draw the background texture - if (Config.backgroundTextureMode > 0) { - double bu1 = 0.0; double bu2 = 1.0; - double bv1 = 0.0; double bv2 = 1.0; - if (Config.backgroundTextureMode == 2) { - // background moves with map if mode is 2 - double bSize = tSize / 256.0; - bu1 = u * bSize; bu2 = (u + w) * bSize; - bv1 = v * bSize; bv2 = (v + h) * bSize; - } - this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - bu1, bv1, bu2, bv2 - ); - } else { - // mode 0, no background texture - Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - } - - // only draw surface map if the request is loaded (view requests are - // loaded by the background thread) - if (this.mw.mapTexture.isLoaded(req)) { - this.mw.mapTexture.bind(); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } - } - - // draw ProfMobius chunk overlay - IMwDataProvider provider = this.drawOverlay(); - - // overlay onDraw event - if (provider != null) { - GL11.glPushMatrix(); - provider.onDraw(this.mapView, this.mapMode); - GL11.glPopMatrix(); - } - - if (this.mapMode.config.circular) { - Render.disableStencil(); - } - - GL11.glPopMatrix(); - } - - private void drawBorder() { - if (this.mapMode.config.circular) { - this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); - } else { - this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); - } - Render.setColour(0xffffffff); - Render.drawTexturedRect( - this.mapMode.x / 0.75, this.mapMode.y / 0.75, - this.mapMode.w / 0.75, this.mapMode.h / 0.75, - 0.0, 0.0, 1.0, 1.0 - ); - } - - private void drawPlayerArrow() { - GL11.glPushMatrix(); - double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); - Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); - this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); - - // the arrow only needs to be rotated if the map is NOT rotated - GL11.glTranslated(p.x, p.y, 0.0); - if (!this.mapMode.config.rotate) { - GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - double arrowSize = this.mapMode.config.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); - Render.drawTexturedRect( - -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - GL11.glPopMatrix(); - } - - private void drawIcons() { - GL11.glPushMatrix(); - - if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - // draw markers - this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); - - // draw player trail - if (this.mw.playerTrail.enabled) { - this.mw.playerTrail.draw(this.mapMode, this.mapView); - } - - // draw north arrow - if (this.mapMode.config.rotate) { - double y = this.mapMode.h / 2.0; - double arrowSize = this.mapMode.config.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); - Render.drawTexturedRect( - -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - } - - GL11.glPopMatrix(); - - // outside of the matrix pop as theplayer arrow - // needs to be drawn without rotation - this.drawPlayerArrow(); - } - - private void drawCoords() { - // draw coordinates - if (this.mapMode.config.coordsEnabled) { - GL11.glPushMatrix(); - GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (Config.coordsMode != Config.coordsModeStringArray[2]) { - GL11.glScalef(0.5f, 0.5f, 1.0f); - } - int offset = 0; - if (Config.coordsMode != Config.coordsModeStringArray[0]) { - Render.drawCentredString(0, 0, this.mapMode.textColour, - "%d, %d, %d", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt - ); - offset += 12; - } - if (Config.undergroundMode) { - Render.drawCentredString( - 0, offset, this.mapMode.textColour,"underground mode" - ); - } - GL11.glPopMatrix(); - } - } - - private IMwDataProvider drawOverlay() { - // draw overlays from registered providers - //for (IMwDataProvider provider : MwAPI.getDataProviders()) - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) { - ArrayList overlays = provider.getChunksOverlay( - this.mapView.getDimension(), - this.mapView.getX(), this.mapView.getZ(), - this.mapView.getMinX(), this.mapView.getMinZ(), - this.mapView.getMaxX(), this.mapView.getMaxZ() - ); - if (overlays != null) { - for (IMwChunkOverlay overlay : overlays) { - paintChunk(this.mapMode, this.mapView, overlay); - } - } - } - return provider; - } - - public void draw() { - - this.mapMode.setScreenRes(); - this.mapView.setMapWH(this.mapMode); - this.mapView.setTextureSize(Config.textureSize); - - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - - // translate to center of minimap - // z is -2000 so that it is drawn above the 3D world, but below GUI - // elements which are typically at -3000 - GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); - - // draw background, the map texture, and enabled overlays - this.drawMap(); - - if (this.mapMode.config.borderMode) { - this.drawBorder(); - } - this.drawIcons(); - - this.drawCoords(); - - // some shader mods seem to need depth testing re-enabled - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); - } - - private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ - int chunkX = overlay.getCoordinates().x; - int chunkZ = overlay.getCoordinates().y; - float filling = overlay.getFilling(); - - Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); - Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); - - topCorner.x = Math.max(mapMode.x, topCorner.x); - topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); - topCorner.y = Math.max(mapMode.y, topCorner.y); - topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); - - botCorner.x = Math.max(mapMode.x, botCorner.x); - botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); - botCorner.y = Math.max(mapMode.y, botCorner.y); - botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); - - double sizeX = (botCorner.x - topCorner.x) * filling; - double sizeY = (botCorner.y - topCorner.y) * filling; - double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; - double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; - - if (overlay.hasBorder()) { - Render.setColour(overlay.getBorderColor()); - Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); - } - - Render.setColour(overlay.getColor()); - Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); - } - - public MapMode getMapMode() - { - return this.mapMode; - } -} - +package mapwriter.map; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.Mw; +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Render; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +public class MapRenderer { + private Mw mw; + private MapMode mapMode; + private MapView mapView; + // accessed by the MwGui to check whether the mouse cursor is near the + // player arrow on the rendered map + public Point.Double playerArrowScreenPos = new Point.Double(0, 0); + + private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { + this.mw = mw; + this.mapMode = mapMode; + this.mapView = mapView; + } + + private void drawMap() { + + int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); + double tSize = (double) this.mw.textureSize; + double zoomScale = (double) (1 << regionZoomLevel); + + // if the texture UV coordinates do not line up with the texture pixels then the texture + // will look blurry when it is drawn to the screen. + // to fix this we round the texture coordinates to the nearest pixel boundary. + // this is unnecessary when zoomed in as the texture will be upscaled and look blurry + // anyway, so it is disabled in this case. + // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture + // pixel boundaries when zoomed in. + + double u, v, w, h; + if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; + v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; + w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; + h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; + } else { + double tSizeInBlocks = tSize * zoomScale; + u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; + v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; + w = (this.mapView.getWidth() / tSizeInBlocks); + h = (this.mapView.getHeight() / tSizeInBlocks); + } + + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + if (this.mapMode.config.circular) { + Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); + } + + if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { + // draw the underground map + this.mw.undergroundMapTexture.requestView(this.mapView); + // underground map needs to have a black background + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + this.mw.undergroundMapTexture.bind(); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } else { + // draw the surface map + MapViewRequest req = new MapViewRequest(this.mapView); + this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); + + // draw the background texture + if (Config.backgroundTextureMode > 0) { + double bu1 = 0.0; double bu2 = 1.0; + double bv1 = 0.0; double bv2 = 1.0; + if (Config.backgroundTextureMode == 2) { + // background moves with map if mode is 2 + double bSize = tSize / 256.0; + bu1 = u * bSize; bu2 = (u + w) * bSize; + bv1 = v * bSize; bv2 = (v + h) * bSize; + } + this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + bu1, bv1, bu2, bv2 + ); + } else { + // mode 0, no background texture + Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + } + + // only draw surface map if the request is loaded (view requests are + // loaded by the background thread) + if (this.mw.mapTexture.isLoaded(req)) { + this.mw.mapTexture.bind(); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } + } + + // draw ProfMobius chunk overlay + IMwDataProvider provider = this.drawOverlay(); + + // overlay onDraw event + if (provider != null) { + GL11.glPushMatrix(); + provider.onDraw(this.mapView, this.mapMode); + GL11.glPopMatrix(); + } + + if (this.mapMode.config.circular) { + Render.disableStencil(); + } + + GL11.glPopMatrix(); + } + + private void drawBorder() { + if (this.mapMode.config.circular) { + this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); + } else { + this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); + } + Render.setColour(0xffffffff); + Render.drawTexturedRect( + this.mapMode.x / 0.75, this.mapMode.y / 0.75, + this.mapMode.w / 0.75, this.mapMode.h / 0.75, + 0.0, 0.0, 1.0, 1.0 + ); + } + + private void drawPlayerArrow() { + GL11.glPushMatrix(); + double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); + Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); + this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); + + // the arrow only needs to be rotated if the map is NOT rotated + GL11.glTranslated(p.x, p.y, 0.0); + if (!this.mapMode.config.rotate) { + GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); + Render.drawTexturedRect( + -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + GL11.glPopMatrix(); + } + + private void drawIcons() { + GL11.glPushMatrix(); + + if (this.mapMode.config.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + // draw markers + this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); + + // draw player trail + if (this.mw.playerTrail.enabled) { + this.mw.playerTrail.draw(this.mapMode, this.mapView); + } + + // draw north arrow + if (this.mapMode.config.rotate) { + double y = this.mapMode.h / 2.0; + double arrowSize = this.mapMode.config.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); + Render.drawTexturedRect( + -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + } + + GL11.glPopMatrix(); + + // outside of the matrix pop as theplayer arrow + // needs to be drawn without rotation + this.drawPlayerArrow(); + } + + private void drawCoords() { + // draw coordinates + if (this.mapMode.config.coordsEnabled) { + GL11.glPushMatrix(); + GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); + if (Config.coordsMode != Config.coordsModeStringArray[2]) { + GL11.glScalef(0.5f, 0.5f, 1.0f); + } + int offset = 0; + if (Config.coordsMode != Config.coordsModeStringArray[0]) { + Render.drawCentredString(0, 0, this.mapMode.textColour, + "%d, %d, %d", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt + ); + offset += 12; + } + if (Config.undergroundMode) { + Render.drawCentredString( + 0, offset, this.mapMode.textColour,"underground mode" + ); + } + GL11.glPopMatrix(); + } + } + + private IMwDataProvider drawOverlay() { + // draw overlays from registered providers + //for (IMwDataProvider provider : MwAPI.getDataProviders()) + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) { + ArrayList overlays = provider.getChunksOverlay( + this.mapView.getDimension(), + this.mapView.getX(), this.mapView.getZ(), + this.mapView.getMinX(), this.mapView.getMinZ(), + this.mapView.getMaxX(), this.mapView.getMaxZ() + ); + if (overlays != null) { + for (IMwChunkOverlay overlay : overlays) { + paintChunk(this.mapMode, this.mapView, overlay); + } + } + } + return provider; + } + + public void draw() { + + this.mapMode.setScreenRes(); + this.mapView.setMapWH(this.mapMode); + this.mapView.setTextureSize(this.mw.textureSize); + + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + + // translate to center of minimap + // z is -2000 so that it is drawn above the 3D world, but below GUI + // elements which are typically at -3000 + GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); + + // draw background, the map texture, and enabled overlays + this.drawMap(); + + if (this.mapMode.config.borderMode) { + this.drawBorder(); + } + this.drawIcons(); + + this.drawCoords(); + + // some shader mods seem to need depth testing re-enabled + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + + private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ + int chunkX = overlay.getCoordinates().x; + int chunkZ = overlay.getCoordinates().y; + float filling = overlay.getFilling(); + + Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); + Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); + + topCorner.x = Math.max(mapMode.x, topCorner.x); + topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); + topCorner.y = Math.max(mapMode.y, topCorner.y); + topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); + + botCorner.x = Math.max(mapMode.x, botCorner.x); + botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); + botCorner.y = Math.max(mapMode.y, botCorner.y); + botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); + + double sizeX = (botCorner.x - topCorner.x) * filling; + double sizeY = (botCorner.y - topCorner.y) * filling; + double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; + double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; + + if (overlay.hasBorder()) { + Render.setColour(overlay.getBorderColor()); + Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); + } + + Render.setColour(overlay.getColor()); + Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); + } + + public MapMode getMapMode() + { + return this.mapMode; + } +} + diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index d71d0fcb..830cee48 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -1,392 +1,392 @@ -package mapwriter.region; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.minecraft.block.Block; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockPos; -import net.minecraft.world.chunk.NibbleArray; -import net.minecraftforge.fml.common.FMLLog; - -import org.apache.logging.log4j.Level; - -public class MwChunk implements IChunk { - public static final int SIZE = 16; - - public final int x; - public final int z; - public final int dimension; - - char[][] dataArray = new char[16][]; - public final byte[][] lightingArray; - public final Map tileentityMap; - - public final byte[] biomeArray; - - public final int maxY; - - public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { - this.x = x; - this.z = z; - this.dimension = dimension; - this.biomeArray = biomeArray; - this.lightingArray = lightingArray; - this.tileentityMap = TileEntityMap; - this.dataArray = data; - int maxY = 0; - for (int y = 0; y < 16; y++) { - if (data[y] != null) { - maxY = (y << 4) + 15; - } - } - this.maxY = maxY; - } - - public String toString() { - return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); - } - - // load from anvil file - public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { - - byte[] biomeArray = null; - byte[][] lsbArray = new byte[16][]; - char[][] data = new char[16][]; - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = new HashMap(); - - DataInputStream dis = null; - RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); - if (!regionFile.isOpen()) { - if (regionFile.exists()) { - regionFile.open(); - } - } - - if (regionFile.isOpen()) { - dis = regionFile.getChunkDataInputStream(x & 31, z & 31); - } - - if (dis != null) { - try { - - //chunk NBT structure: - // - //COMPOUND "" - //COMPOUND "level" - // INT "xPos" - // INT "zPos" - // LONG "LastUpdate" - // BYTE "TerrainPopulated" - // BYTE_ARRAY "Biomes" - // INT_ARRAY "HeightMap" - // LIST(COMPOUND) "Sections" - // BYTE "Y" - // BYTE_ARRAY "Blocks" - // BYTE_ARRAY "Add" - // BYTE_ARRAY "Data" - // BYTE_ARRAY "BlockLight" - // BYTE_ARRAY "SkyLight" - // END - // LIST(COMPOUND) "Entities" - // LIST(COMPOUND) "TileEntities" - // LIST(COMPOUND) "TileTicks" - //END - //END - NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); - NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); - - int xNbt = level.getInteger("xPos"); - int zNbt = level.getInteger("zPos"); - - if ((xNbt != x) || (zNbt != z)) { - RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); - } - - NBTTagList sections = level.getTagList("Sections", 10); - - for (int k = 0; k < sections.tagCount(); ++k) - { - NBTTagCompound section = sections.getCompoundTagAt(k); - int y = section.getByte("Y"); - lsbArray[y & 0xf] = section.getByteArray("Blocks"); - NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); - NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; - - data[y & 0xf] = new char[lsbArray[y].length]; - - for (int l = 0; l < data[y & 0xf].length; ++l) - { - int i1 = l & 15; - int j1 = l >> 8 & 15; - int k1 = l >> 4 & 15; - int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; - data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); - } - } - - biomeArray = level.getByteArray("Biomes"); - - NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); - - if (nbttaglist2 != null) - { - for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) - { - NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); - TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); - if (tileentity != null) - { - TileEntityMap.put(tileentity.getPos(), tileentity); - } - } - } - - - } catch (IOException e) { - RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); - } finally { - try { dis.close(); } - catch (IOException e) { - RegionManager.logError("MwChunk.read: %s while closing input stream", e); - } - } - //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); - } else { - //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); - } - - return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); - } - - public boolean isEmpty() { - return (this.maxY <= 0); - } - - public int getBiome(int x, int z) { - return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; - } - - public int getLightValue(int x, int y, int z) { - //int yi = (y >> 4) & 0xf; - //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; - - //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); - return 15; - } - - public int getMaxY() { - return this.maxY; - } - - public int getBlockAndMetadata(int x, int y, int z) { - int yi = (y >> 4) & 0xf; - int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - int lsb = 0; - int msb = 0; - int meta = 0; - - BlockPos pos = new BlockPos(x,y,z); - - char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; - - //check if the block has a tileentity if so use the blockdata in the tileentity - //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) - if (this.tileentityMap.containsKey(pos)) - { - - TileEntity value = (TileEntity)this.tileentityMap.get(pos); - NBTTagCompound tag = new NBTTagCompound(); - value.writeToNBT(tag); - int id = 0; - - if (tag.getString("id") == "savedMultipart") - { - String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); - int end = material.indexOf("_"); - - //block with metadata - if (end != -1) - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); - - lsb = (id & 255); - - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - meta = Integer.parseInt(material.substring(end+1)); - } - //block without metadata - else - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); - - lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - } - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - else if (tag.getString("id") =="TileEntityCarpentersBlock") - { - NBTTagList TagList = tag.getTagList("cbAttrList", 10); - String sid = TagList.getCompoundTagAt(0).getString("id"); - String smeta = TagList.getCompoundTagAt(0).getString("Damage"); - if (sid != "") - { - id = Integer.parseInt(sid.substring(0, sid.length()-1)); - - lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - if (smeta != "") - { - meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); - } - - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - } - } - - //return ((offset & 1) == 1) ? - // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : - return (int)data; - } - - //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data - private NBTTagCompound writeChunkToNBT() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound.setTag("Level", nbttagcompound1); - - nbttagcompound1.setInteger("xPos", this.x); - nbttagcompound1.setInteger("zPos", this.z); - - NBTTagList nbttaglist = new NBTTagList(); - - int i = 16; - NBTTagCompound nbttagcompound2; - - for (int y = 0; y < this.dataArray.length; y++) - { - if (this.dataArray[y] != null) - { - byte[] abyte = new byte[this.dataArray[y].length]; - NibbleArray nibblearray = new NibbleArray(); - NibbleArray nibblearray1 = null; - - for (int k = 0; k < this.dataArray[y].length; ++k) - { - char c0 = this.dataArray[y][k]; - int l = k & 15; - int i1 = k >> 8 & 15; - int j1 = k >> 4 & 15; - - if (c0 >> 12 != 0) - { - if (nibblearray1 == null) - { - nibblearray1 = new NibbleArray(); - } - - nibblearray1.set(l, i1, j1, c0 >> 12); - } - - abyte[k] = (byte)(c0 >> 4 & 255); - nibblearray.set(l, i1, j1, c0 & 15); - } - - - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Y", (byte)y); - nbttagcompound2.setByteArray("Blocks", abyte); - - if (nibblearray1 != null) - { - nbttagcompound2.setByteArray("Add", nibblearray1.getData()); - } - - nbttagcompound2.setByteArray("Data", nibblearray.getData()); - nbttaglist.appendTag(nbttagcompound2); - } - - nbttagcompound1.setTag("Sections", nbttaglist); - } - nbttagcompound1.setByteArray("Biomes", this.biomeArray); - - NBTTagList nbttaglist2 = new NBTTagList(); - Iterator iterator1; - - NBTTagList nbttaglist3 = new NBTTagList(); - - iterator1 = this.tileentityMap.values().iterator(); - - while (iterator1.hasNext()) - { - TileEntity tileentity = (TileEntity)iterator1.next(); - nbttagcompound2 = new NBTTagCompound(); - try { - tileentity.writeToNBT(nbttagcompound2); - nbttaglist3.appendTag(nbttagcompound2); - } - catch (Exception e) - { - FMLLog.log(Level.ERROR, e, - "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", - tileentity.getClass().getName()); - } - } - nbttagcompound1.setTag("TileEntities", nbttaglist3); - - return nbttagcompound; - } - - public synchronized boolean write(RegionFileCache regionFileCache) { - boolean error = false; - RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); - if (!regionFile.isOpen()) { - error = regionFile.open(); - } - if (!error) { - DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); - if (dos != null) { - //Nbt chunkNbt = this.getNbt(); - try { - //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); - //chunkNbt.writeElement(dos); - //use minecraft build in save tool for saving the Anvil Data - CompressedStreamTools.write(writeChunkToNBT(), dos); - } catch (IOException e) { - RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); - error = true; - } finally { - try { dos.close(); } - catch (IOException e) { - RegionManager.logError("%s while closing chunk data output stream", e); - } - } - } else { - RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); - } - } else { - RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); - } - - return error; - } -} +package mapwriter.region; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import net.minecraft.block.Block; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.NibbleArray; +import net.minecraftforge.fml.common.FMLLog; + +import org.apache.logging.log4j.Level; + +public class MwChunk implements IChunk { + public static final int SIZE = 16; + + public final int x; + public final int z; + public final int dimension; + + char[][] dataArray = new char[16][]; + public final byte[][] lightingArray; + public final Map tileentityMap; + + public final byte[] biomeArray; + + public final int maxY; + + public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { + this.x = x; + this.z = z; + this.dimension = dimension; + this.biomeArray = biomeArray; + this.lightingArray = lightingArray; + this.tileentityMap = TileEntityMap; + this.dataArray = data; + int maxY = 0; + for (int y = 0; y < 16; y++) { + if (data[y] != null) { + maxY = (y << 4) + 15; + } + } + this.maxY = maxY; + } + + public String toString() { + return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); + } + + // load from anvil file + public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { + + byte[] biomeArray = null; + byte[][] lsbArray = new byte[16][]; + char[][] data = new char[16][]; + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = new HashMap(); + + DataInputStream dis = null; + RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); + if (!regionFile.isOpen()) { + if (regionFile.exists()) { + regionFile.open(); + } + } + + if (regionFile.isOpen()) { + dis = regionFile.getChunkDataInputStream(x & 31, z & 31); + } + + if (dis != null) { + try { + + //chunk NBT structure: + // + //COMPOUND "" + //COMPOUND "level" + // INT "xPos" + // INT "zPos" + // LONG "LastUpdate" + // BYTE "TerrainPopulated" + // BYTE_ARRAY "Biomes" + // INT_ARRAY "HeightMap" + // LIST(COMPOUND) "Sections" + // BYTE "Y" + // BYTE_ARRAY "Blocks" + // BYTE_ARRAY "Add" + // BYTE_ARRAY "Data" + // BYTE_ARRAY "BlockLight" + // BYTE_ARRAY "SkyLight" + // END + // LIST(COMPOUND) "Entities" + // LIST(COMPOUND) "TileEntities" + // LIST(COMPOUND) "TileTicks" + //END + //END + NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); + NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); + + int xNbt = level.getInteger("xPos"); + int zNbt = level.getInteger("zPos"); + + if ((xNbt != x) || (zNbt != z)) { + RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); + } + + NBTTagList sections = level.getTagList("Sections", 10); + + for (int k = 0; k < sections.tagCount(); ++k) + { + NBTTagCompound section = sections.getCompoundTagAt(k); + int y = section.getByte("Y"); + lsbArray[y & 0xf] = section.getByteArray("Blocks"); + NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); + NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; + + data[y & 0xf] = new char[lsbArray[y].length]; + + for (int l = 0; l < data[y & 0xf].length; ++l) + { + int i1 = l & 15; + int j1 = l >> 8 & 15; + int k1 = l >> 4 & 15; + int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; + data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); + } + } + + biomeArray = level.getByteArray("Biomes"); + + NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); + + if (nbttaglist2 != null) + { + for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) + { + NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); + TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); + if (tileentity != null) + { + TileEntityMap.put(tileentity.getPos(), tileentity); + } + } + } + + + } catch (IOException e) { + RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); + } finally { + try { dis.close(); } + catch (IOException e) { + RegionManager.logError("MwChunk.read: %s while closing input stream", e); + } + } + //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); + } else { + //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); + } + + return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); + } + + public boolean isEmpty() { + return (this.maxY <= 0); + } + + public int getBiome(int x, int z) { + return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; + } + + public int getLightValue(int x, int y, int z) { + //int yi = (y >> 4) & 0xf; + //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; + + //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); + return 15; + } + + public int getMaxY() { + return this.maxY; + } + + public int getBlockAndMetadata(int x, int y, int z) { + int yi = (y >> 4) & 0xf; + int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + int lsb = 0; + int msb = 0; + int meta = 0; + + BlockPos pos = new BlockPos(x,y,z); + + char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; + + //check if the block has a tileentity if so use the blockdata in the tileentity + //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) + if (this.tileentityMap.containsKey(pos)) + { + + TileEntity value = (TileEntity)this.tileentityMap.get(pos); + NBTTagCompound tag = new NBTTagCompound(); + value.writeToNBT(tag); + int id = 0; + + if (tag.getString("id") == "savedMultipart") + { + String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); + int end = material.indexOf("_"); + + //block with metadata + if (end != -1) + { + id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); + + lsb = (id & 255); + + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + + meta = Integer.parseInt(material.substring(end+1)); + } + //block without metadata + else + { + id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); + + lsb = (id & 255); + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + } + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } + else if (tag.getString("id") =="TileEntityCarpentersBlock") + { + NBTTagList TagList = tag.getTagList("cbAttrList", 10); + String sid = TagList.getCompoundTagAt(0).getString("id"); + String smeta = TagList.getCompoundTagAt(0).getString("Damage"); + if (sid != "") + { + id = Integer.parseInt(sid.substring(0, sid.length()-1)); + + lsb = (id & 255); + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + + if (smeta != "") + { + meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); + } + + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } + } + } + + //return ((offset & 1) == 1) ? + // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : + return (int)data; + } + + //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data + private NBTTagCompound writeChunkToNBT() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound.setTag("Level", nbttagcompound1); + + nbttagcompound1.setInteger("xPos", this.x); + nbttagcompound1.setInteger("zPos", this.z); + + NBTTagList nbttaglist = new NBTTagList(); + + int i = 16; + NBTTagCompound nbttagcompound2; + + for (int y = 0; y < this.dataArray.length; y++) + { + if (this.dataArray[y] != null) + { + byte[] abyte = new byte[this.dataArray[y].length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < this.dataArray[y].length; ++k) + { + char c0 = this.dataArray[y][k]; + int l = k & 15; + int i1 = k >> 8 & 15; + int j1 = k >> 4 & 15; + + if (c0 >> 12 != 0) + { + if (nibblearray1 == null) + { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte)(c0 >> 4 & 255); + nibblearray.set(l, i1, j1, c0 & 15); + } + + + nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Y", (byte)y); + nbttagcompound2.setByteArray("Blocks", abyte); + + if (nibblearray1 != null) + { + nbttagcompound2.setByteArray("Add", nibblearray1.getData()); + } + + nbttagcompound2.setByteArray("Data", nibblearray.getData()); + nbttaglist.appendTag(nbttagcompound2); + } + + nbttagcompound1.setTag("Sections", nbttaglist); + } + nbttagcompound1.setByteArray("Biomes", this.biomeArray); + + NBTTagList nbttaglist2 = new NBTTagList(); + Iterator iterator1; + + NBTTagList nbttaglist3 = new NBTTagList(); + + iterator1 = this.tileentityMap.values().iterator(); + + while (iterator1.hasNext()) + { + TileEntity tileentity = (TileEntity)iterator1.next(); + nbttagcompound2 = new NBTTagCompound(); + try { + tileentity.writeToNBT(nbttagcompound2); + nbttaglist3.appendTag(nbttagcompound2); + } + catch (Exception e) + { + FMLLog.log(Level.ERROR, e, + "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", + tileentity.getClass().getName()); + } + } + nbttagcompound1.setTag("TileEntities", nbttaglist3); + + return nbttagcompound; + } + + public synchronized boolean write(RegionFileCache regionFileCache) { + boolean error = false; + RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); + if (!regionFile.isOpen()) { + error = regionFile.open(); + } + if (!error) { + DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); + if (dos != null) { + //Nbt chunkNbt = this.getNbt(); + try { + //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); + //chunkNbt.writeElement(dos); + //use minecraft build in save tool for saving the Anvil Data + CompressedStreamTools.write(writeChunkToNBT(), dos); + } catch (IOException e) { + RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); + error = true; + } finally { + try { dos.close(); } + catch (IOException e) { + RegionManager.logError("%s while closing chunk data output stream", e); + } + } + } else { + RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); + } + } else { + RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 7ad6680e..831d97ab 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,148 +1,148 @@ -package mapwriter.util; - -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.config.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return Reference.patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - Logging.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } - - public static String getWorldName() { - String worldName; - - if (Minecraft.getMinecraft().isIntegratedServerRunning()) - { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - else - { - worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; - if (!Config.portNumberInWorldNameEnabled) - { - worldName = worldName.substring(0, worldName.indexOf(":")); - } - else - { - worldName = worldName.replace(":", "_"); - } - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } -} +package mapwriter.util; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import mapwriter.config.Config; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + //send an ingame chat message and console log + public static void printBoth(String msg) { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } + + public static String getWorldName() { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + worldName = worldName.replace(":", "_"); + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } +} From 14dbf68f757703b41c93668be2a336b4cb7cfe60 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 13 May 2015 14:29:58 +0200 Subject: [PATCH 032/109] fixed a derp on folder naming --- src/main/java/mapwriter/Mw.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 2096d880..89e4b467 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -283,7 +283,7 @@ public void load() { } } - if (this.mc.isSingleplayer()) { + if (!this.mc.isSingleplayer()) { this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), Utils.getWorldName()); } else { this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), Utils.getWorldName()); From 88881666d9bfd351741909587ba68cc3a47cba98 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 20 May 2015 22:47:07 +0200 Subject: [PATCH 033/109] Fix for grass not being dark. seems that getting the texture colour for grass returns dirt. so just overwrite it with the default gray --- src/main/java/mapwriter/BlockColourGen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 1bad0f0d..22d5dd9b 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -66,6 +66,8 @@ private static int adjustBlockColourFromType(BlockColours bc, int blockAndMeta, // they also look too dark if the render colour is applied. blockColour |= 0xff000000; break; + case GRASS: + blockColour = 0xff9b9b9b; default: break; } From 075239683b67d672a6940d1fe002b07a436c6d79 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 20 May 2015 22:54:27 +0200 Subject: [PATCH 034/109] Moved to RenderTickEvent instead of RenderGameOverlayEvent.Post this seems to fix the flickering in chat. (Dont ask me why this fixes it) --- .../java/mapwriter/forge/ClientProxy.java | 10 ++++---- .../java/mapwriter/forge/EventHandler.java | 24 +++++++++++++++---- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 31012b9e..5711e014 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -19,11 +19,13 @@ public void preInit(File configFile) } public void load() { - MinecraftForge.EVENT_BUS.register(new EventHandler(Mw.getInstance())); + EventHandler eventHandler = new EventHandler(Mw.getInstance()); + MinecraftForge.EVENT_BUS.register(eventHandler); + FMLCommonHandler.instance().bus().register(eventHandler); - Object eventhandler = new MwKeyHandler(); - FMLCommonHandler.instance().bus().register(eventhandler); - MinecraftForge.EVENT_BUS.register(eventhandler); + MwKeyHandler keyEventHandler = new MwKeyHandler(); + FMLCommonHandler.instance().bus().register(keyEventHandler); + MinecraftForge.EVENT_BUS.register(keyEventHandler); } public void postInit() { diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 824d6099..fa773603 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -5,14 +5,14 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.DamageSource; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.ChunkEvent; -import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; +import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent; public class EventHandler { @@ -74,10 +74,24 @@ public void eventPlayerDeath(LivingDeathEvent event) { } } + //@SubscribeEvent + //public void renderMap(RenderGameOverlayEvent.Post event){ + // if(event.type == RenderGameOverlayEvent.ElementType.ALL){ + // Mw.getInstance().onTick(); + // } + //} + + //using the FML render tick event because RenderGameOverlayEvent.Post creates flickering @SubscribeEvent - public void renderMap(RenderGameOverlayEvent.Post event){ - if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - Mw.getInstance().onTick(); + public void onTick(RenderTickEvent event) + { + if (event.phase.equals(Phase.START)) + { + return; + } + if (Mw.getInstance().ready) + { + Mw.getInstance().onTick(); } } } From 81080684fedcfe307092fd7f52082a94c4a5e154 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 20 May 2015 23:38:20 +0200 Subject: [PATCH 035/109] upped version number to indicate fixes --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index 1a36d4b4..9a760c83 100644 --- a/build.properties +++ b/build.properties @@ -3,4 +3,4 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.1.1334 mcp_version=snapshot_20150319 -mod_version=2.2.3 +mod_version=2.2.4 From 3ffeb59c4a771ee2ffc901d7d5dd8b3fe643dc04 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 20 May 2015 23:45:21 +0200 Subject: [PATCH 036/109] a fix so that the minecraft version is in the final jar file --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a787cee0..cfc5b816 100644 --- a/build.gradle +++ b/build.gradle @@ -70,8 +70,10 @@ processResources } } +version = "${project.minecraft.version}-${project.version}" + jar { -classifier = 'universal' +// = 'universal' } task sourceJar(type: Jar) { From 9a2308340e9a7cba4bd2120859e82a4449a8a273 Mon Sep 17 00:00:00 2001 From: Fansana Date: Sun, 31 May 2015 21:22:47 +0200 Subject: [PATCH 037/109] adding default port to save file when port is missing. --- src/main/java/mapwriter/util/Utils.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 831d97ab..c2ebb161 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -122,7 +122,7 @@ public static String getWorldName() { worldName = (server != null) ? server.getFolderName() : "sp_world"; } else - { + { worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; if (!Config.portNumberInWorldNameEnabled) { @@ -130,7 +130,11 @@ public static String getWorldName() { } else { - worldName = worldName.replace(":", "_"); + if(worldName.indexOf(":")==-1){//standard port is missing. Adding it + worldName += "_25565"; + } else { + worldName = worldName.replace(":", "_"); + } } } From 90561a4f436fa5fa89849d0559bca85aa8934bca Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 4 Jun 2015 23:05:05 +0200 Subject: [PATCH 038/109] updated imports, Changed margin configuration to fixed positions fixed the repositioning of the minimap when ingame. upped version number. --- build.properties | 2 +- src/main/java/mapwriter/Mw.java | 2 +- src/main/java/mapwriter/config/Config.java | 15 --- .../ConfigurationHandler.java | 31 ++--- .../java/mapwriter/config/MapModeConfig.java | 35 ++--- .../java/mapwriter/forge/ClientProxy.java | 2 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 21 +-- src/main/java/mapwriter/map/MapRenderer.java | 2 +- src/main/java/mapwriter/map/MiniMap.java | 6 - src/main/java/mapwriter/map/Trail.java | 2 +- .../java/mapwriter/map/mapmode/MapMode.java | 123 +++++++++++------- 11 files changed, 113 insertions(+), 128 deletions(-) rename src/main/java/mapwriter/{handler => config}/ConfigurationHandler.java (86%) diff --git a/build.properties b/build.properties index 9a760c83..3403c1c1 100644 --- a/build.properties +++ b/build.properties @@ -3,4 +3,4 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.1.1334 mcp_version=snapshot_20150319 -mod_version=2.2.4 +mod_version=2.2.5 diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 89e4b467..f6dca1bf 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -3,12 +3,12 @@ import java.io.File; import mapwriter.config.Config; +import mapwriter.config.ConfigurationHandler; import mapwriter.config.WorldConfig; import mapwriter.forge.MwForge; import mapwriter.forge.MwKeyHandler; import mapwriter.gui.MwGui; import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.handler.ConfigurationHandler; import mapwriter.map.MapTexture; import mapwriter.map.MapView; import mapwriter.map.Marker; diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 4ee8b16e..49964fe6 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -1,23 +1,8 @@ package mapwriter.config; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; import mapwriter.util.Reference; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; public class Config { - public static final String[] miniMapPositionStringArray = { - "unchanged", - "top right", - "top left", - "bottom right", - "bottom left" - }; public static final String[] coordsModeStringArray = { "disabled", "small", diff --git a/src/main/java/mapwriter/handler/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java similarity index 86% rename from src/main/java/mapwriter/handler/ConfigurationHandler.java rename to src/main/java/mapwriter/config/ConfigurationHandler.java index dd50254a..312f1976 100644 --- a/src/main/java/mapwriter/handler/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -1,12 +1,8 @@ -package mapwriter.handler; +package mapwriter.config; import java.io.File; -import mapwriter.Mw; -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; import mapwriter.util.Reference; -import mapwriter.util.Utils; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @@ -76,10 +72,7 @@ public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent public static void setMapModeDefaults() { Config.fullScreenMap.heightPercent = -1; - Config.fullScreenMap.marginTop = 0; - Config.fullScreenMap.marginBottom = 0; - Config.fullScreenMap.marginLeft = 0; - Config.fullScreenMap.marginRight = 0; + Config.fullScreenMap.Position = "FullScreen"; Config.fullScreenMap.borderMode = false; Config.fullScreenMap.playerArrowSize = 5; Config.fullScreenMap.markerSize = 5; @@ -90,31 +83,27 @@ public static void setMapModeDefaults() ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "enabled", Config.fullScreenMap.enabled).setShowInGui(false); ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginTop", Config.fullScreenMap.marginTop).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginLeft", Config.fullScreenMap.marginLeft).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "marginRight", Config.fullScreenMap.marginRight).setShowInGui(false); ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "Position", Config.fullScreenMap.Position).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "Position", Config.fullScreenMap.Position).setDefaultValue("FullScreen"); + Config.largeMap.heightPercent = -1; - Config.largeMap.marginTop = 10; - Config.largeMap.marginBottom = 40; - Config.largeMap.marginLeft = 40; - Config.largeMap.marginRight = 40; + Config.largeMap.Position = "Large"; Config.largeMap.playerArrowSize = 5; Config.largeMap.markerSize = 5; Config.largeMap.coordsEnabled = true; ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", Config.largeMap.enabled).setRequiresWorldRestart(true); - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "Position", Config.largeMap.Position).setShowInGui(false); + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "Position", Config.largeMap.Position).setDefaultValue("Large"); Config.smallMap.heightPercent = 30; - Config.smallMap.marginTop = 10; - Config.smallMap.marginBottom = -1; - Config.smallMap.marginLeft = -1; - Config.smallMap.marginRight = 10; + Config.smallMap.Position = Config.smallMap.miniMapPositionStringArray[0]; Config.smallMap.playerArrowSize = 4; Config.smallMap.markerSize = 3; Config.smallMap.coordsEnabled = true; diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index 2349f2ce..f2b5038e 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -1,19 +1,22 @@ package mapwriter.config; -import java.util.ArrayList; -import java.util.List; - import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; import net.minecraftforge.fml.client.config.IConfigElement; -public class MapModeConfig { - +public class MapModeConfig { public final String configCategory; + public static final String[] miniMapPositionStringArray = { + "top right", + "top left", + "bottom right", + "bottom left" + }; + + public boolean Changed = false; + public boolean enabled = true; public boolean rotate = true; public boolean circular = true; @@ -23,12 +26,10 @@ public class MapModeConfig { public int markerSize = 5; public int trailMarkerSize = 3; public int alphaPercent = 100; - - public int marginTop = 0; - public int marginBottom = 0; - public int marginLeft = 0; - public int marginRight = 0; public int heightPercent = -1; + public String Position = miniMapPositionStringArray[0]; + + public MapModeConfig(String configCategory) { this.configCategory = configCategory; @@ -42,17 +43,17 @@ public void loadConfig() { this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, "mw.config.map.alphaPercent"); this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, "mw.config.map.heightPercent"); - this.marginTop = ConfigurationHandler.configuration.getInt("marginTop", this.configCategory, this.marginTop, -1, 320, "mw.config.map.marginTop"); - this.marginBottom = ConfigurationHandler.configuration.getInt("marginBottom", this.configCategory, this.marginBottom, -1, 320, "mw.config.map.marginBottom"); - this.marginLeft = ConfigurationHandler.configuration.getInt("marginLeft", this.configCategory, this.marginLeft, -1, 320, "mw.config.map.marginLeft"); - this.marginRight = ConfigurationHandler.configuration.getInt("marginRight", this.configCategory, this.marginRight, -1, 320, "mw.config.map.marginRight"); - + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, "mw.config.map.rotate"); this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, "mw.config.map.circular"); this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, "mw.config.map.coordsEnabled"); this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderMode, "mw.config.map.borderMode"); + this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, miniMapPositionStringArray[0], "mw.config.map.Position", miniMapPositionStringArray); + this.trailMarkerSize = Math.max(1, this.markerSize - 1); + + this.Changed = true; } public IConfigElement categoryElement(String name, String tooltip_key) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 5711e014..b4ae6cc1 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -4,7 +4,7 @@ import mapwriter.Mw; import mapwriter.api.MwAPI; -import mapwriter.handler.ConfigurationHandler; +import mapwriter.config.ConfigurationHandler; import mapwriter.overlay.OverlayGrid; import mapwriter.overlay.OverlaySlime; import net.minecraftforge.common.MinecraftForge; diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index a7f79faa..0c300675 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -2,32 +2,21 @@ import java.util.ArrayList; import java.util.List; -import java.util.Set; import mapwriter.config.Config; -import mapwriter.handler.ConfigurationHandler; -import mapwriter.map.mapmode.MapMode; +import mapwriter.config.ConfigurationHandler; import mapwriter.util.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; -import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.AddModOverrideEntry; -import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.ModOverridesEntry; -import net.minecraftforge.common.ForgeChunkManager; -import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.GuiConfigEntries; -import net.minecraftforge.fml.client.config.GuiUtils; -import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; -import net.minecraftforge.fml.client.config.IConfigElement; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.CategoryEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.NumberSliderEntry; +import net.minecraftforge.fml.client.config.GuiUtils; +import net.minecraftforge.fml.client.config.IConfigElement; public class ModGuiConfig extends GuiConfig { diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 5dfe420f..09fb086b 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -257,7 +257,7 @@ private IMwDataProvider drawOverlay() { } public void draw() { - + this.mapMode.checkChanges(); this.mapMode.setScreenRes(); this.mapView.setMapWH(this.mapMode); this.mapView.setTextureSize(this.mw.textureSize); diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index 932968f0..8142791b 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -8,7 +8,6 @@ import mapwriter.map.mapmode.LargeMapMode; import mapwriter.map.mapmode.MapMode; import mapwriter.map.mapmode.SmallMapMode; -import mapwriter.util.Reference; public class MiniMap { private Mw mw; @@ -77,11 +76,6 @@ public MapRenderer nextOverlayMode(int increment) { return this.currentMap; } - public void toggleRotating() { - boolean rotate = this.smallMapMode.toggleRotating(); - this.largeMapMode.setRotating(rotate); - } - // draw the map overlay, player arrow, and markers public void drawCurrentMap() { if (this.currentMap != null) { diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java index 1b2c4100..39fd55f5 100644 --- a/src/main/java/mapwriter/map/Trail.java +++ b/src/main/java/mapwriter/map/Trail.java @@ -4,7 +4,7 @@ import java.util.LinkedList; import mapwriter.Mw; -import mapwriter.handler.ConfigurationHandler; +import mapwriter.config.ConfigurationHandler; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Reference; import mapwriter.util.Render; diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 0fc6e49a..0d04a9c0 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -1,18 +1,11 @@ package mapwriter.map.mapmode; import java.awt.Point; -import java.util.ArrayList; -import java.util.List; import mapwriter.config.MapModeConfig; -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.handler.ConfigurationHandler; import mapwriter.map.MapView; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; -import net.minecraftforge.fml.client.config.ConfigGuiType; -import net.minecraftforge.fml.client.config.DummyConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; public class MapMode { private int sw = 320; @@ -29,6 +22,11 @@ public class MapMode { public int wPixels = 50; public int hPixels = 50; + public int marginLeft = 10; + public int marginRight = -1; + public int marginTop = -1; + public int marginBottom = 10; + // config settings public int textX = 0; @@ -39,6 +37,7 @@ public class MapMode { public MapMode(MapModeConfig config) { this.config = config; + updateMargin(); } public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { @@ -56,25 +55,64 @@ public void setScreenRes() { this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); } - public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { - this.config.marginTop = marginTop; - this.config.marginBottom = marginBottom; - this.config.marginLeft = marginLeft; - this.config.marginRight = marginRight; - this.update(); - } - - public void setHeightPercent(int heightPercent) { - this.config.heightPercent = heightPercent; - this.update(); + public void checkChanges() + { + if (this.config.Changed) + { + this.updateMargin(); + this.update(); + this.config.Changed = false; + } } - public void toggleHeightPercent() { - int i = (this.config.heightPercent / 5) + 1; - if (i > 12) { - i = 1; + private void updateMargin() + { + //top right + if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[0])) + { + marginTop = 10; + marginBottom = -1; + marginLeft = -1; + marginRight = 10; + } + //top left + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[1])) + { + marginTop = 10; + marginBottom = -1; + marginLeft = 10; + marginRight = -1; + } + //botom right + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[2])) + { + marginTop = -1; + marginBottom = 40; + marginLeft = -1; + marginRight = 10; + } + //botom left + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[3])) + { + marginTop = -1; + marginBottom = 40; + marginLeft = 10; + marginRight = -1; + } + else if (this.config.Position.equals("FullScreen")) + { + marginTop = 0; + marginBottom = 0; + marginLeft = 0; + marginRight = 0; + } + else if (this.config.Position.equals("Large")) + { + marginTop = 10; + marginBottom = 40; + marginLeft = 40; + marginRight = 40; } - this.setHeightPercent(i * 5); } private void update() { @@ -82,14 +120,14 @@ private void update() { int x, y; // calculate map x position and width - if ((this.config.marginLeft >= 0) && (this.config.marginRight >= 0)) { - x = this.config.marginLeft; - this.w = this.sw - this.config.marginLeft - this.config.marginRight; - } else if (this.config.marginLeft >= 0) { - x = this.config.marginLeft; + if ((marginLeft >= 0) && (marginRight >= 0)) { + x = marginLeft; + this.w = this.sw - marginLeft - marginRight; + } else if (marginLeft >= 0) { + x = marginLeft; this.w = size; - } else if (this.config.marginRight >= 0) { - x = this.sw - size - this.config.marginRight; + } else if (marginRight >= 0) { + x = this.sw - size - marginRight; this.w = size; } else { x = (this.sw - size) / 2; @@ -97,14 +135,14 @@ private void update() { } // calculate map y position and height - if ((this.config.marginTop >= 0) && (this.config.marginBottom >= 0)) { - y = this.config.marginTop; - this.h = this.sh - this.config.marginTop - this.config.marginBottom; - } else if (this.config.marginTop >= 0) { - y = this.config.marginTop; + if ((marginTop >= 0) && (marginBottom >= 0)) { + y = marginTop; + this.h = this.sh - marginTop - marginBottom; + } else if (marginTop >= 0) { + y = marginTop; this.h = size; - } else if (this.config.marginBottom >= 0) { - y = this.sh - size - this.config.marginBottom; + } else if (marginBottom >= 0) { + y = this.sh - size - marginBottom; this.h = size; } else { y = (this.sh - size) / 2; @@ -137,17 +175,6 @@ private void update() { // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); } - public void setRotating(boolean enabled) { - this.config.rotate = enabled; - this.config.circular = enabled; - this.update(); - } - - public boolean toggleRotating() { - this.setRotating(!this.config.rotate); - return this.config.rotate; - } - public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); From f87bebadbc3f7d687e44574312277d9d16500a2a Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 5 Jun 2015 01:36:53 +0200 Subject: [PATCH 039/109] Split the settings for the different mapmodes so it wont clutter the config file with useless settings. added default values for the settings --- src/main/java/mapwriter/config/Config.java | 66 +++++++++------- .../config/ConfigurationHandler.java | 78 +++++-------------- .../java/mapwriter/config/MapModeConfig.java | 68 ++++++++-------- .../mapwriter/config/largeMapModeConfig.java | 48 ++++++++++++ .../mapwriter/config/smallMapModeConfig.java | 38 +++++++++ src/main/java/mapwriter/map/MapRenderer.java | 9 ++- 6 files changed, 189 insertions(+), 118 deletions(-) create mode 100644 src/main/java/mapwriter/config/largeMapModeConfig.java create mode 100644 src/main/java/mapwriter/config/smallMapModeConfig.java diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 49964fe6..5d47cbfa 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -3,11 +3,6 @@ import mapwriter.util.Reference; public class Config { - public static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; public static final String[] backgroundModeStringArray = { "none", "static", @@ -15,31 +10,50 @@ public class Config { }; // configuration options - public static boolean linearTextureScaling = true; - public static String coordsMode = coordsModeStringArray[0]; - public static boolean undergroundMode = false; - public static boolean teleportEnabled = true; - public static String teleportCommand = "tp"; - public static int defaultTeleportHeight = 80; - public static int zoomOutLevels = 5; - public static int zoomInLevels = -5; - public static boolean useSavedBlockColours = false; - public static int maxChunkSaveDistSq = 128 * 128; - public static boolean mapPixelSnapEnabled = true; - public static int configTextureSize = 2048; - public static int maxDeathMarkers = 3; - public static int chunksPerTick = 5; - public static boolean portNumberInWorldNameEnabled = true; - public static String saveDirOverride = ""; - public static boolean regionFileOutputEnabledSP = true; - public static boolean regionFileOutputEnabledMP = true; - public static int backgroundTextureMode = 0; + public static boolean linearTextureScalingDef = true; + public static boolean linearTextureScaling = linearTextureScalingDef; + public static boolean undergroundModeDef = false; + public static boolean undergroundMode = undergroundModeDef; + public static boolean teleportEnabledDef = true; + public static boolean teleportEnabled = teleportEnabledDef; + public static String teleportCommandDef = "tp"; + public static String teleportCommand = teleportCommandDef; + public static int defaultTeleportHeightDef = 80; + public static int defaultTeleportHeight = defaultTeleportHeightDef; + public static int zoomOutLevelsDef = 5; + public static int zoomOutLevels = zoomOutLevelsDef; + public static int zoomInLevelsDef = -5; + public static int zoomInLevels = zoomInLevelsDef; + public static boolean useSavedBlockColoursDef = false; + public static boolean useSavedBlockColours = useSavedBlockColoursDef; + public static int maxChunkSaveDistSqDef = 128 * 128; + public static int maxChunkSaveDistSq = maxChunkSaveDistSqDef; + public static boolean mapPixelSnapEnabledDef = true; + public static boolean mapPixelSnapEnabled = mapPixelSnapEnabledDef; + public static int configTextureSizeDef = 2048; + public static int configTextureSize = configTextureSizeDef; + public static int maxDeathMarkersDef = 3; + public static int maxDeathMarkers = maxDeathMarkersDef; + public static int chunksPerTickDef = 5; + public static int chunksPerTick = chunksPerTickDef; + public static boolean portNumberInWorldNameEnabledDef = true; + public static boolean portNumberInWorldNameEnabled = portNumberInWorldNameEnabledDef; + public static String saveDirOverrideDef = ""; + public static String saveDirOverride = saveDirOverrideDef; + public static boolean regionFileOutputEnabledSPDef = true; + public static boolean regionFileOutputEnabledSP = regionFileOutputEnabledSPDef; + public static boolean regionFileOutputEnabledMPDef = true; + public static boolean regionFileOutputEnabledMP = regionFileOutputEnabledMPDef; + public static int backgroundTextureModeDef = 0; + public static int backgroundTextureMode = backgroundTextureModeDef; //World configuration Options public static int overlayModeIndex = 0; + public static int overlayModeIndexDef = 0; public static int overlayZoomLevel = 0; + public static int overlayZoomLevelDef = 0; - public static MapModeConfig largeMap = new MapModeConfig(Reference.catLargeMapConfig); - public static MapModeConfig smallMap = new MapModeConfig(Reference.catSmallMapConfig); + public static largeMapModeConfig largeMap = new largeMapModeConfig(Reference.catLargeMapConfig); + public static smallMapModeConfig smallMap = new smallMapModeConfig(Reference.catSmallMapConfig); public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); } diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 312f1976..6d2e598c 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -25,28 +25,27 @@ public static void init(File configFile) public static void loadConfig() { - Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScaling, "mw.config.linearTextureScaling"); - Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColours, "mw.config.useSavedBlockColours"); - Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabled, "mw.config.teleportEnabled"); - Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommand, "mw.config.teleportCommand"); - Config.coordsMode = configuration.getString("coordsMode", Reference.catOptions, Config.coordsMode, "mw.config.coordsMode", Config.coordsModeStringArray); - Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSq, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); - Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabled, "mw.config.mapPixelSnapEnabled"); - Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkers, 0, 1000, "mw.config.maxDeathMarkers"); - Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTick, 1, 500, "mw.config.chunksPerTick"); - Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverride, "mw.config.saveDirOverride"); - Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabled, "mw.config.portNumberInWorldNameEnabled"); - Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundMode, "mw.config.undergroundMode"); - Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSP, "mw.config.regionFileOutputEnabledSP"); - Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMP, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureMode, 0, 1, "mw.config.backgroundTextureMode"); + Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingDef, "mw.config.linearTextureScaling"); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColoursDef, "mw.config.useSavedBlockColours"); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabledDef, "mw.config.teleportEnabled"); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommandDef, "mw.config.teleportCommand"); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSqDef, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabledDef, "mw.config.mapPixelSnapEnabled"); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkersDef, 0, 1000, "mw.config.maxDeathMarkers"); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTickDef, 1, 500, "mw.config.chunksPerTick"); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverrideDef, "mw.config.saveDirOverride"); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabledDef, "mw.config.portNumberInWorldNameEnabled"); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); + Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, 0, 1, "mw.config.backgroundTextureMode"); - Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevels, 1, 256, "mw.config.zoomOutLevels"); - Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevels, 1, 256, "mw.config.zoomInLevels"); + Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); + Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSize, 1024, 4096, "mw.config.textureSize"); + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "mw.config.textureSize"); - Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndex, 0, 1000, "mw.config.overlayModeIndex"); + Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "mw.config.overlayModeIndex"); Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); Config.fullScreenMap.loadConfig(); @@ -71,43 +70,8 @@ public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent public static void setMapModeDefaults() { - Config.fullScreenMap.heightPercent = -1; - Config.fullScreenMap.Position = "FullScreen"; - Config.fullScreenMap.borderMode = false; - Config.fullScreenMap.playerArrowSize = 5; - Config.fullScreenMap.markerSize = 5; - Config.fullScreenMap.alphaPercent = 100; - Config.fullScreenMap.rotate = false; - Config.fullScreenMap.circular = false; - Config.fullScreenMap.coordsEnabled = false; - - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "enabled", Config.fullScreenMap.enabled).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "heightPercent", Config.fullScreenMap.heightPercent).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "borderMode", Config.fullScreenMap.borderMode).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "rotate", Config.fullScreenMap.rotate).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "circular", Config.fullScreenMap.circular).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "coordsEnabled", Config.fullScreenMap.coordsEnabled).setShowInGui(false); - - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "Position", Config.fullScreenMap.Position).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catFullMapConfig, "Position", Config.fullScreenMap.Position).setDefaultValue("FullScreen"); - - Config.largeMap.heightPercent = -1; - Config.largeMap.Position = "Large"; - Config.largeMap.playerArrowSize = 5; - Config.largeMap.markerSize = 5; - Config.largeMap.coordsEnabled = true; - - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", Config.largeMap.enabled).setRequiresWorldRestart(true); - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "heightPercent", Config.largeMap.heightPercent).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "Position", Config.largeMap.Position).setShowInGui(false); - ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "Position", Config.largeMap.Position).setDefaultValue("Large"); - - Config.smallMap.heightPercent = 30; - Config.smallMap.Position = Config.smallMap.miniMapPositionStringArray[0]; - Config.smallMap.playerArrowSize = 4; - Config.smallMap.markerSize = 3; - Config.smallMap.coordsEnabled = true; - - ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", Config.smallMap.enabled).setRequiresWorldRestart(true); + Config.fullScreenMap.setDefaults(); + Config.largeMap.setDefaults(); + Config.smallMap.setDefaults(); } } \ No newline at end of file diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index f2b5038e..0ec1aebf 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -6,7 +6,12 @@ import net.minecraftforge.fml.client.config.IConfigElement; public class MapModeConfig { - public final String configCategory; + public final String configCategory; + public static final String[] coordsModeStringArray = { + "disabled", + "small", + "large" + }; public static final String[] miniMapPositionStringArray = { "top right", @@ -16,20 +21,29 @@ public class MapModeConfig { }; public boolean Changed = false; - - public boolean enabled = true; - public boolean rotate = true; - public boolean circular = true; - public boolean coordsEnabled = false; - public boolean borderMode = true; - public int playerArrowSize = 5; - public int markerSize = 5; - public int trailMarkerSize = 3; - public int alphaPercent = 100; - public int heightPercent = -1; - public String Position = miniMapPositionStringArray[0]; - + public boolean enabledDef = true; + public boolean enabled = enabledDef; + public boolean rotateDef = false; + public boolean rotate = rotateDef; + public boolean circularDef = false; + public boolean circular = circularDef; + public String coordsModeDef = coordsModeStringArray[0]; + public String coordsMode = coordsModeDef; + public boolean borderModeDef = false; + public boolean borderMode = borderModeDef; + public int playerArrowSizeDef = 5; + public int playerArrowSize = playerArrowSizeDef; + public int markerSizeDef = 5; + public int markerSize = markerSizeDef; + public int trailMarkerSizeDef = 3; + public int trailMarkerSize = trailMarkerSizeDef; + public int alphaPercentDef = 100; + public int alphaPercent = alphaPercentDef; + public int heightPercentDef = -1; + public int heightPercent = heightPercentDef; + public String PositionDef = "FullScreen"; + public String Position = PositionDef; public MapModeConfig(String configCategory) { this.configCategory = configCategory; @@ -37,30 +51,22 @@ public MapModeConfig(String configCategory) { public void loadConfig() { // get options from config file - this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabled, "mw.config.map.enabled"); - this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSize, 1, 20, "mw.config.map.playerArrowSize"); - this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSize, 1, 20, "mw.config.map.markerSize"); - this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercent, 0, 100, "mw.config.map.alphaPercent"); - - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercent, 0, 100, "mw.config.map.heightPercent"); + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSizeDef, 1, 20, "mw.config.map.playerArrowSize"); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSizeDef, 1, 20, "mw.config.map.markerSize"); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "mw.config.map.alphaPercent"); - this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotate, "mw.config.map.rotate"); - this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circular, "mw.config.map.circular"); - this.coordsEnabled = ConfigurationHandler.configuration.getBoolean("coordsEnabled", this.configCategory, this.coordsEnabled, "mw.config.map.coordsEnabled"); - this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderMode, "mw.config.map.borderMode"); - - this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, miniMapPositionStringArray[0], "mw.config.map.Position", miniMapPositionStringArray); - this.trailMarkerSize = Math.max(1, this.markerSize - 1); this.Changed = true; } + public void setDefaults() + { + } + public IConfigElement categoryElement(String name, String tooltip_key) - { - ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); - + { return new DummyCategoryElement(name, tooltip_key, new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); } -} +} \ No newline at end of file diff --git a/src/main/java/mapwriter/config/largeMapModeConfig.java b/src/main/java/mapwriter/config/largeMapModeConfig.java new file mode 100644 index 00000000..71ebd3ba --- /dev/null +++ b/src/main/java/mapwriter/config/largeMapModeConfig.java @@ -0,0 +1,48 @@ +package mapwriter.config; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.util.Reference; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; + +public class largeMapModeConfig extends MapModeConfig +{ + public largeMapModeConfig(String configCategory) { + super(configCategory); + } + + @Override + public void loadConfig() + { + super.loadConfig(); + this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabledDef, "mw.config.map.enabled"); + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotateDef, "mw.config.map.rotate"); + this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circularDef, "mw.config.map.circular"); + this.coordsMode = ConfigurationHandler.configuration.getString("coordsMode", this.configCategory, this.coordsModeDef, "mw.config.map.coordsMode", coordsModeStringArray); + this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderModeDef, "mw.config.map.borderMode"); + } + + @Override + public void setDefaults() + { + this.rotateDef = true; + this.circularDef = true; + this.coordsModeDef = coordsModeStringArray[1]; + this.borderModeDef = true; + this.heightPercentDef = -1; + this.PositionDef = "Large"; + + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", this.enabled).setRequiresWorldRestart(true); + } + + @Override + public IConfigElement categoryElement(String name, String tooltip_key) + { + ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); + + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); + } + +} diff --git a/src/main/java/mapwriter/config/smallMapModeConfig.java b/src/main/java/mapwriter/config/smallMapModeConfig.java new file mode 100644 index 00000000..cd53f170 --- /dev/null +++ b/src/main/java/mapwriter/config/smallMapModeConfig.java @@ -0,0 +1,38 @@ +package mapwriter.config; + +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; +import mapwriter.util.Reference; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.fml.client.config.IConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; + +public class smallMapModeConfig extends largeMapModeConfig +{ + public smallMapModeConfig(String configCategory) + { + super(configCategory); + } + + @Override + public void loadConfig() + { + super.loadConfig(); + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); + this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); + } + + @Override + public void setDefaults() + { + this.rotateDef = true; + this.circularDef = true; + this.coordsModeDef = coordsModeStringArray[1]; + this.borderModeDef = true; + this.playerArrowSizeDef = 4; + this.markerSizeDef = 3; + this.heightPercentDef = 30; + this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; + + ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); + } +} diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 09fb086b..68f9268f 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -8,6 +8,7 @@ import mapwriter.api.IMwDataProvider; import mapwriter.api.MwAPI; import mapwriter.config.Config; +import mapwriter.config.MapModeConfig; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Render; import net.minecraft.util.ResourceLocation; @@ -211,14 +212,15 @@ private void drawIcons() { private void drawCoords() { // draw coordinates - if (this.mapMode.config.coordsEnabled) { + if (!this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[0])) + { GL11.glPushMatrix(); GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (Config.coordsMode != Config.coordsModeStringArray[2]) { + if (this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[1])) + { GL11.glScalef(0.5f, 0.5f, 1.0f); } int offset = 0; - if (Config.coordsMode != Config.coordsModeStringArray[0]) { Render.drawCentredString(0, 0, this.mapMode.textColour, "%d, %d, %d", this.mw.playerXInt, @@ -226,7 +228,6 @@ private void drawCoords() { this.mw.playerZInt ); offset += 12; - } if (Config.undergroundMode) { Render.drawCentredString( 0, offset, this.mapMode.textColour,"underground mode" From 46da22ea6a6612451181515a11049327ffac9e24 Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 5 Jun 2015 15:59:26 +0200 Subject: [PATCH 040/109] Switched GL11 calls to the GlStateManager. fixes some graphic bugs moved back to the forge render event. --- src/main/java/mapwriter/Mw.java | 2 +- .../java/mapwriter/forge/EventHandler.java | 20 +---- src/main/java/mapwriter/map/MapRenderer.java | 44 +++++----- src/main/java/mapwriter/util/Render.java | 85 ++++++++++--------- src/main/java/mapwriter/util/Texture.java | 8 +- 5 files changed, 74 insertions(+), 85 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index f6dca1bf..93722e0a 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -55,7 +55,7 @@ public class Mw { public int playerZInt = 0; public double playerHeading = 0.0; public int playerDimension = 0; - public double mapRotationDegrees = 0.0; + public float mapRotationDegrees = 0.0f; // instances of components public MapTexture mapTexture = null; diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index fa773603..dfd45e7d 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -74,24 +74,10 @@ public void eventPlayerDeath(LivingDeathEvent event) { } } - //@SubscribeEvent - //public void renderMap(RenderGameOverlayEvent.Post event){ - // if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - // Mw.getInstance().onTick(); - // } - //} - - //using the FML render tick event because RenderGameOverlayEvent.Post creates flickering @SubscribeEvent - public void onTick(RenderTickEvent event) - { - if (event.phase.equals(Phase.START)) - { - return; - } - if (Mw.getInstance().ready) - { - Mw.getInstance().onTick(); + public void renderMap(RenderGameOverlayEvent.Post event){ + if(event.type == RenderGameOverlayEvent.ElementType.ALL){ + Mw.getInstance().onTick(); } } } diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 68f9268f..d768d1dd 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -11,6 +11,7 @@ import mapwriter.config.MapModeConfig; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Render; +import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -62,11 +63,10 @@ private void drawMap() { w = (this.mapView.getWidth() / tSizeInBlocks); h = (this.mapView.getHeight() / tSizeInBlocks); } - - GL11.glPushMatrix(); + GlStateManager.pushMatrix(); if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } if (this.mapMode.config.circular) { Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); @@ -128,16 +128,15 @@ private void drawMap() { // overlay onDraw event if (provider != null) { - GL11.glPushMatrix(); + GlStateManager.pushMatrix(); provider.onDraw(this.mapView, this.mapMode); - GL11.glPopMatrix(); + GlStateManager.popMatrix(); } if (this.mapMode.config.circular) { Render.disableStencil(); } - - GL11.glPopMatrix(); + GlStateManager.popMatrix(); } private void drawBorder() { @@ -155,15 +154,15 @@ private void drawBorder() { } private void drawPlayerArrow() { - GL11.glPushMatrix(); + GlStateManager.pushMatrix(); double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); // the arrow only needs to be rotated if the map is NOT rotated - GL11.glTranslated(p.x, p.y, 0.0); + GlStateManager.translate(p.x, p.y, 0.0); if (!this.mapMode.config.rotate) { - GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + GlStateManager.rotate(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } double arrowSize = this.mapMode.config.playerArrowSize; @@ -173,14 +172,14 @@ private void drawPlayerArrow() { -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, 0.0, 0.0, 1.0, 1.0 ); - GL11.glPopMatrix(); + GlStateManager.popMatrix(); } private void drawIcons() { - GL11.glPushMatrix(); + GlStateManager.pushMatrix(); if (this.mapMode.config.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } // draw markers @@ -202,8 +201,7 @@ private void drawIcons() { 0.0, 0.0, 1.0, 1.0 ); } - - GL11.glPopMatrix(); + GlStateManager.popMatrix(); // outside of the matrix pop as theplayer arrow // needs to be drawn without rotation @@ -214,11 +212,11 @@ private void drawCoords() { // draw coordinates if (!this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[0])) { - GL11.glPushMatrix(); - GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); + GlStateManager.pushMatrix(); + GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); if (this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[1])) { - GL11.glScalef(0.5f, 0.5f, 1.0f); + GlStateManager.scale(0.5f, 0.5f, 1.0f); } int offset = 0; Render.drawCentredString(0, 0, this.mapMode.textColour, @@ -233,7 +231,7 @@ private void drawCoords() { 0, offset, this.mapMode.textColour,"underground mode" ); } - GL11.glPopMatrix(); + GlStateManager.popMatrix(); } } @@ -263,13 +261,13 @@ public void draw() { this.mapView.setMapWH(this.mapMode); this.mapView.setTextureSize(this.mw.textureSize); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); // translate to center of minimap // z is -2000 so that it is drawn above the 3D world, but below GUI // elements which are typically at -3000 - GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); + GlStateManager.translate(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); // draw background, the map texture, and enabled overlays this.drawMap(); @@ -283,7 +281,7 @@ public void draw() { // some shader mods seem to need depth testing re-enabled GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); + GlStateManager.popMatrix(); } private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index a54348ea..eb84e23c 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -2,6 +2,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; @@ -27,18 +28,19 @@ public static void setColourWithAlphaPercent(int colour, int alphaPercent) { } public static void setColour(int colour) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor4f( + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.color( (float) ((colour >> 16) & 0xff) / 255.0f, (float) ((colour >> 8) & 0xff) / 255.0f, (float) ((colour) & 0xff) / 255.0f, (float) ((colour >> 24) & 0xff) / 255.0f); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.disableBlend(); } public static void resetColour() { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); } public static int multiplyColours(int c1, int c2) { @@ -155,9 +157,9 @@ public static void drawTexturedRect(double x, double y, double w, double h) { // draw rectangle with texture UV coordinates specified (so only part of the texture fills the rectangle). public static void drawTexturedRect(double x, double y, double w, double h, double u1, double v1, double u2, double v2) { try { - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableTexture2D(); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawingQuads(); @@ -167,7 +169,7 @@ public static void drawTexturedRect(double x, double y, double w, double h, doub renderer.addVertexWithUV(x + w, y + h, zDepth, u2, v2); //renderer.finishDrawing(); tessellator.draw(); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.disableBlend(); } catch (NullPointerException e) { Logging.log("MwRender.drawTexturedRect: null pointer exception"); } @@ -176,9 +178,9 @@ public static void drawTexturedRect(double x, double y, double w, double h, doub public static void drawArrow(double x, double y, double angle, double length) { // angle the back corners will be drawn at relative to the pointing angle double arrowBackAngle = 0.75D * Math.PI; - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawing(GL11.GL_TRIANGLE_FAN); @@ -188,14 +190,14 @@ public static void drawArrow(double x, double y, double angle, double length) { renderer.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); //renderer.finishDrawing(); tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); } public static void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawing(GL11.GL_TRIANGLES); @@ -204,14 +206,14 @@ public static void drawTriangle(double x1, double y1, double x2, double y2, doub renderer.addVertex(x3, y3, zDepth); //renderer.finishDrawing(); tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); } public static void drawRect(double x, double y, double w, double h) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawingQuads(); @@ -221,14 +223,14 @@ public static void drawRect(double x, double y, double w, double h) { renderer.addVertex(x + w, y + h, zDepth); //renderer.finishDrawing(); tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); } public static void drawCircle(double x, double y, double r) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawing(GL11.GL_TRIANGLE_FAN); @@ -241,14 +243,14 @@ public static void drawCircle(double x, double y, double r) { } //renderer.finishDrawing(); tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); } public static void drawCircleBorder(double x, double y, double r, double width) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); renderer.startDrawing(GL11.GL_TRIANGLE_STRIP); @@ -262,8 +264,8 @@ public static void drawCircleBorder(double x, double y, double r, double width) } //renderer.finishDrawing(); tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); } public static void drawRectBorder(double x, double y, double w, double h, double bw) { @@ -295,12 +297,12 @@ public static void drawCentredString(int x, int y, int colour, String formatStri } public static void setCircularStencil(double x, double y, double r) { - GL11.glEnable(GL11.GL_DEPTH_TEST); + GlStateManager.depthFunc(GL11.GL_DEPTH_TEST); // disable drawing to the color buffer. // circle will only be drawn to depth buffer. GL11.glColorMask(false, false, false, false); // enable writing to depth buffer - GL11.glDepthMask(true); + GlStateManager.depthMask(true); // Clearing the depth buffer causes problems with shader mods. // I guess we just have to hope that the rest of the depth buffer @@ -316,7 +318,7 @@ public static void setCircularStencil(double x, double y, double r) { //GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); // always write to depth buffer - GL11.glDepthFunc(GL11.GL_ALWAYS); + GlStateManager.depthFunc(GL11.GL_ALWAYS); // draw stencil pattern (filled circle at z = 1000.0) Render.setColour(0xffffffff); @@ -327,17 +329,18 @@ public static void setCircularStencil(double x, double y, double r) { // re-enable drawing to colour buffer GL11.glColorMask(true, true, true, true); // disable drawing to depth buffer - GL11.glDepthMask(false); + GlStateManager.depthMask(false); // only draw pixels with z values that are greater // than the value in the depth buffer. // The overlay is drawn at 2000 so this will pass inside // the circle (2000 > 1000) but not outside (2000 <= 3000). - GL11.glDepthFunc(GL11.GL_GREATER); + GlStateManager.depthFunc(GL11.GL_GREATER); } public static void disableStencil() { - GL11.glDepthMask(true); - GL11.glDepthFunc(GL11.GL_LEQUAL); + GlStateManager.depthMask(true); + GlStateManager.depthFunc(GL11.GL_LEQUAL); + GlStateManager.disableDepth(); GL11.glDisable(GL11.GL_DEPTH_TEST); } diff --git a/src/main/java/mapwriter/util/Texture.java b/src/main/java/mapwriter/util/Texture.java index 5139ef0f..19ffc176 100644 --- a/src/main/java/mapwriter/util/Texture.java +++ b/src/main/java/mapwriter/util/Texture.java @@ -2,6 +2,8 @@ import java.nio.IntBuffer; +import net.minecraft.client.renderer.GlStateManager; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -14,7 +16,7 @@ public class Texture { // allocate new texture and fill from IntBuffer public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int textureWrap) { - this.id = GL11.glGenTextures(); + this.id = GlStateManager.generateTexture(); this.w = w; this.h = h; this.pixelBuf = Utils.allocateDirectIntBuffer(w * h); @@ -44,7 +46,7 @@ public Texture(int id) { public synchronized void close() { if (this.id != 0) { try { - GL11.glDeleteTextures(this.id); + GlStateManager.deleteTexture(this.id); } catch (NullPointerException e) { Logging.log("MwTexture.close: null pointer exception (texture %d)", this.id); } @@ -97,7 +99,7 @@ public synchronized int getRGB(int x, int y) { } public void bind() { - GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.id); + GlStateManager.bindTexture(this.id); } // set texture scaling and wrapping parameters From 4621b532e63006510cc1e437891c6b13dc2f0291 Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 5 Jun 2015 16:12:50 +0200 Subject: [PATCH 041/109] fix for: [CLIENT] [SEVERE] ########## GL ERROR ########## [CLIENT] [SEVERE] @ Post render [CLIENT] [SEVERE] 1280: Invalid enum --- src/main/java/mapwriter/util/Render.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index eb84e23c..8a41714e 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -297,7 +297,7 @@ public static void drawCentredString(int x, int y, int colour, String formatStri } public static void setCircularStencil(double x, double y, double r) { - GlStateManager.depthFunc(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_DEPTH_TEST); // disable drawing to the color buffer. // circle will only be drawn to depth buffer. GL11.glColorMask(false, false, false, false); From a119e5f7dab4df18679641ff163f01c0850499f3 Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 5 Jun 2015 16:59:52 +0200 Subject: [PATCH 042/109] check every render tick if position changed in config. (fixes map not changing position) Fix so that the large map uses the right dimensions fix to make the square map not rotatable --- .../java/mapwriter/config/MapModeConfig.java | 4 ---- .../mapwriter/config/largeMapModeConfig.java | 1 + src/main/java/mapwriter/map/MapRenderer.java | 8 +++---- .../java/mapwriter/map/mapmode/MapMode.java | 24 +++++++++---------- 4 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index 0ec1aebf..de70d62d 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -19,8 +19,6 @@ public class MapModeConfig { "bottom right", "bottom left" }; - - public boolean Changed = false; public boolean enabledDef = true; public boolean enabled = enabledDef; @@ -56,8 +54,6 @@ public void loadConfig() { this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "mw.config.map.alphaPercent"); this.trailMarkerSize = Math.max(1, this.markerSize - 1); - - this.Changed = true; } public void setDefaults() diff --git a/src/main/java/mapwriter/config/largeMapModeConfig.java b/src/main/java/mapwriter/config/largeMapModeConfig.java index 71ebd3ba..57b31684 100644 --- a/src/main/java/mapwriter/config/largeMapModeConfig.java +++ b/src/main/java/mapwriter/config/largeMapModeConfig.java @@ -32,6 +32,7 @@ public void setDefaults() this.borderModeDef = true; this.heightPercentDef = -1; this.PositionDef = "Large"; + this.Position = this.PositionDef; ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", this.enabled).setRequiresWorldRestart(true); } diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index d768d1dd..ad6433c5 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -65,7 +65,7 @@ private void drawMap() { } GlStateManager.pushMatrix(); - if (this.mapMode.config.rotate) { + if (this.mapMode.config.rotate && this.mapMode.config.circular == true) { GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } if (this.mapMode.config.circular) { @@ -161,7 +161,7 @@ private void drawPlayerArrow() { // the arrow only needs to be rotated if the map is NOT rotated GlStateManager.translate(p.x, p.y, 0.0); - if (!this.mapMode.config.rotate) { + if (!this.mapMode.config.rotate || this.mapMode.config.circular == false) { GlStateManager.rotate(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } @@ -178,7 +178,7 @@ private void drawPlayerArrow() { private void drawIcons() { GlStateManager.pushMatrix(); - if (this.mapMode.config.rotate) { + if (this.mapMode.config.rotate && this.mapMode.config.circular == true) { GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } @@ -256,7 +256,7 @@ private IMwDataProvider drawOverlay() { } public void draw() { - this.mapMode.checkChanges(); + this.mapMode.updateMargin(); this.mapMode.setScreenRes(); this.mapView.setMapWH(this.mapMode); this.mapView.setTextureSize(this.mw.textureSize); diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 0d04a9c0..256e47b5 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -22,10 +22,12 @@ public class MapMode { public int wPixels = 50; public int hPixels = 50; - public int marginLeft = 10; - public int marginRight = -1; - public int marginTop = -1; - public int marginBottom = 10; + public int marginTop = 10; + public int marginBottom = -1; + public int marginLeft = -1; + public int marginRight = 10; + + public String lastPos = MapModeConfig.miniMapPositionStringArray[0]; // config settings @@ -55,18 +57,13 @@ public void setScreenRes() { this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); } - public void checkChanges() + public void updateMargin() { - if (this.config.Changed) + if (this.lastPos.equals(this.config.Position)) { - this.updateMargin(); - this.update(); - this.config.Changed = false; + return; } - } - - private void updateMargin() - { + //top right if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[0])) { @@ -113,6 +110,7 @@ else if (this.config.Position.equals("Large")) marginLeft = 40; marginRight = 40; } + this.update(); } private void update() { From fd72cf42e2479856e14687927fa8aa0f8c146ac7 Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 5 Jun 2015 17:20:45 +0200 Subject: [PATCH 043/109] changed backgroundTextureMode to a string with fixed values --- src/main/java/mapwriter/config/Config.java | 4 ++-- src/main/java/mapwriter/config/ConfigurationHandler.java | 3 +-- src/main/java/mapwriter/map/MapRenderer.java | 6 ++++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 5d47cbfa..8c9c5822 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -44,8 +44,8 @@ public class Config { public static boolean regionFileOutputEnabledSP = regionFileOutputEnabledSPDef; public static boolean regionFileOutputEnabledMPDef = true; public static boolean regionFileOutputEnabledMP = regionFileOutputEnabledMPDef; - public static int backgroundTextureModeDef = 0; - public static int backgroundTextureMode = backgroundTextureModeDef; + public static String backgroundTextureModeDef = backgroundModeStringArray[0]; + public static String backgroundTextureMode = backgroundTextureModeDef; //World configuration Options public static int overlayModeIndex = 0; diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 6d2e598c..9b86e7e0 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -38,8 +38,7 @@ public static void loadConfig() Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getInt("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, 0, 1, "mw.config.backgroundTextureMode"); - + Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureModeDef", Config.backgroundModeStringArray); Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index ad6433c5..452e2708 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -90,10 +90,12 @@ private void drawMap() { this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); // draw the background texture - if (Config.backgroundTextureMode > 0) { + if (!Config.backgroundTextureMode.equals(Config.backgroundModeStringArray[0])) + { double bu1 = 0.0; double bu2 = 1.0; double bv1 = 0.0; double bv2 = 1.0; - if (Config.backgroundTextureMode == 2) { + if (Config.backgroundTextureMode.equals(Config.backgroundModeStringArray[2])) + { // background moves with map if mode is 2 double bSize = tSize / 256.0; bu1 = u * bSize; bu2 = (u + w) * bSize; From 6a294e8150d5cab0b08331f9ff23e6efa4489b86 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 15 Jun 2015 23:32:18 +0200 Subject: [PATCH 044/109] Increased forge version en MCP mappings --- build.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.properties b/build.properties index 3403c1c1..7f3b8fc4 100644 --- a/build.properties +++ b/build.properties @@ -1,6 +1,6 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 -forge_version=11.14.1.1334 -mcp_version=snapshot_20150319 +forge_version=11.14.3.1450 +mcp_version=snapshot_20150615 mod_version=2.2.5 From e501f2ff0b6474613dc36badaf9b2b1606a9c1c1 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 22 Jun 2015 14:47:49 +0200 Subject: [PATCH 045/109] Moved resoursce location to the Reference Class --- src/main/java/mapwriter/map/MapRenderer.java | 18 ++++++------------ src/main/java/mapwriter/util/Reference.java | 8 ++++++++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index 452e2708..cf58cb78 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -10,9 +10,9 @@ import mapwriter.config.Config; import mapwriter.config.MapModeConfig; import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Reference; import mapwriter.util.Render; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -23,12 +23,6 @@ public class MapRenderer { // accessed by the MwGui to check whether the mouse cursor is near the // player arrow on the rendered map public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { this.mw = mw; @@ -101,7 +95,7 @@ private void drawMap() { bu1 = u * bSize; bu2 = (u + w) * bSize; bv1 = v * bSize; bv2 = (v + h) * bSize; } - this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); + this.mw.mc.renderEngine.bindTexture(Reference.backgroundTexture); Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); Render.drawTexturedRect( this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, @@ -143,9 +137,9 @@ private void drawMap() { private void drawBorder() { if (this.mapMode.config.circular) { - this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); + this.mw.mc.renderEngine.bindTexture(Reference.roundMapTexture); } else { - this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); + this.mw.mc.renderEngine.bindTexture(Reference.squareMapTexture); } Render.setColour(0xffffffff); Render.drawTexturedRect( @@ -169,7 +163,7 @@ private void drawPlayerArrow() { double arrowSize = this.mapMode.config.playerArrowSize; Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); + this.mw.mc.renderEngine.bindTexture(Reference.playerArrowTexture); Render.drawTexturedRect( -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, 0.0, 0.0, 1.0, 1.0 @@ -197,7 +191,7 @@ private void drawIcons() { double y = this.mapMode.h / 2.0; double arrowSize = this.mapMode.config.playerArrowSize; Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); + this.mw.mc.renderEngine.bindTexture(Reference.northArrowTexture); Render.drawTexturedRect( -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, 0.0, 0.0, 1.0, 1.0 diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index d3bdb2dc..16577b7d 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -2,6 +2,8 @@ import java.util.regex.Pattern; +import net.minecraft.util.ResourceLocation; + public final class Reference { public static final String MOD_ID = "MapWriter"; @@ -26,5 +28,11 @@ public final class Reference public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + } From dd6b4d60fcb065f18420b050122ea76dbc66bc60 Mon Sep 17 00:00:00 2001 From: Thijs Date: Thu, 25 Jun 2015 10:38:04 +0200 Subject: [PATCH 046/109] fixed a wrong name in buildscript --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index cfc5b816..84933804 100644 --- a/build.gradle +++ b/build.gradle @@ -110,7 +110,7 @@ gradle.taskGraph.whenReady { taskGraph -> if (!taskGraph.allTasks.findAll{ it.name == 'eclipseClasspath' }.empty) { gradle.buildFinished { println '----------------------------------------------------------------------' - print "Please set the Eclipse classpath variable 'GRADLE_USER_HOME' in Preferences " + print "Please set the Eclipse classpath variable 'GRADLE_CACHE' in Preferences " println "-> Java -> Build path -> Classpath Variable to $gradle.gradleUserHomeDir" println '----------------------------------------------------------------------' } From df123957d11fc90c59b96c094e9d89bbd06ecb39 Mon Sep 17 00:00:00 2001 From: Thijs Date: Thu, 25 Jun 2015 13:20:15 +0200 Subject: [PATCH 047/109] Fixed standing compile warnings --- src/main/java/mapwriter/ChunkManager.java | 305 +++---- .../java/mapwriter/config/MapModeConfig.java | 1 - .../mapwriter/config/smallMapModeConfig.java | 72 +- .../java/mapwriter/forge/EventHandler.java | 2 - src/main/java/mapwriter/map/MiniMap.java | 6 +- .../map/mapmode/FullScreenMapMode.java | 1 - .../mapwriter/map/mapmode/LargeMapMode.java | 1 - .../mapwriter/map/mapmode/SmallMapMode.java | 1 - .../java/mapwriter/region/ChunkRender.java | 2 - src/main/java/mapwriter/region/MwChunk.java | 780 +++++++++--------- src/main/java/mapwriter/util/Logging.java | 2 - src/main/java/mapwriter/util/Utils.java | 379 +++++---- 12 files changed, 804 insertions(+), 748 deletions(-) diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index 3e4cc446..55092a0e 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -1,152 +1,155 @@ -package mapwriter; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import mapwriter.config.Config; -import mapwriter.region.MwChunk; -import mapwriter.tasks.SaveChunkTask; -import mapwriter.tasks.UpdateSurfaceChunksTask; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.storage.ExtendedBlockStorage; - -public class ChunkManager { - public Mw mw; - private boolean closed = false; - private CircularHashMap chunkMap = new CircularHashMap(); - - private static final int VISIBLE_FLAG = 0x01; - private static final int VIEWED_FLAG = 0x02; - - public ChunkManager(Mw mw) { - this.mw = mw; - } - - public synchronized void close() { - this.closed = true; - this.saveChunks(); - this.chunkMap.clear(); - } - - // create MwChunk from Minecraft chunk. - // only MwChunk's should be used in the background thread. - // make this a full copy of chunk data to prevent possible race conditions <-- done - public static MwChunk copyToMwChunk(Chunk chunk) { - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = new HashMap(); - TileEntityMap.putAll(chunk.getTileEntityMap()); - char[][] dataArray = new char[16][]; - - ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); - if (storageArrays != null) { - for (ExtendedBlockStorage storage : storageArrays) { - if (storage != null) { - int y = (storage.getYLocation() >> 4) & 0xf; - dataArray[y] = storage.getData(); - lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; - } - } - } - - return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), - dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); - } - - public synchronized void addChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - this.chunkMap.put(chunk, 0); - } - } - - public synchronized void removeChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? - int flags = this.chunkMap.get(chunk); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(chunk); - } - this.chunkMap.remove(chunk); - } - } - - public synchronized void saveChunks() { - for (Map.Entry entry : this.chunkMap.entrySet()) { - int flags = entry.getValue(); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(entry.getKey()); - } - } - } - - public void updateUndergroundChunks() { - int chunkArrayX = (this.mw.playerXInt >> 4) - 1; - int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; - MwChunk[] chunkArray = new MwChunk[9]; - for (int z = 0; z < 3; z++) { - for (int x = 0; x < 3; x++) { - Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( - chunkArrayX + x, - chunkArrayZ + z - ); - if (!chunk.isEmpty()) { - chunkArray[(z * 3) + x] = copyToMwChunk(chunk); - } - } - } - } - - public void updateSurfaceChunks() { - int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); - MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; - for (int i = 0; i < chunksToUpdate; i++) { - Map.Entry entry = this.chunkMap.getNextEntry(); - if (entry != null) { - // if this chunk is within a certain distance to the player then - // add it to the viewed set - Chunk chunk = entry.getKey(); - - int flags = entry.getValue(); - if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { - flags |= (VISIBLE_FLAG | VIEWED_FLAG); - } else { - flags &= ~VISIBLE_FLAG; - } - entry.setValue(flags); - - if ((flags & VISIBLE_FLAG) != 0) { - chunkArray[i] = copyToMwChunk(chunk); - } else { - chunkArray[i] = null; - } - } - } - - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - public void onTick() { - if (!this.closed) { - if ((this.mw.tickCounter & 0xf) == 0) { - this.updateUndergroundChunks(); - } else { - this.updateSurfaceChunks(); - } - } - } - - public void forceChunks(MwChunk[] chunkArray){ - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - private void addSaveChunkTask(Chunk chunk) { - if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || - (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { - if (!chunk.isEmpty()) { - this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); - } - } - } +package mapwriter; + +import java.util.Arrays; +import java.util.Map; + +import mapwriter.config.Config; +import mapwriter.region.MwChunk; +import mapwriter.tasks.SaveChunkTask; +import mapwriter.tasks.UpdateSurfaceChunksTask; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +import com.google.common.collect.Maps; + +public class ChunkManager { + public Mw mw; + private boolean closed = false; + private CircularHashMap chunkMap = new CircularHashMap(); + + private static final int VISIBLE_FLAG = 0x01; + private static final int VIEWED_FLAG = 0x02; + + public ChunkManager(Mw mw) { + this.mw = mw; + } + + public synchronized void close() { + this.closed = true; + this.saveChunks(); + this.chunkMap.clear(); + } + + // create MwChunk from Minecraft chunk. + // only MwChunk's should be used in the background thread. + // make this a full copy of chunk data to prevent possible race conditions <-- done + public static MwChunk copyToMwChunk(Chunk chunk) { + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = Maps.newHashMap(); + TileEntityMap = Utils.checkedMapByCopy(chunk.getTileEntityMap(), BlockPos.class, TileEntity.class, false); + char[][] dataArray = new char[16][]; + + ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); + if (storageArrays != null) { + for (ExtendedBlockStorage storage : storageArrays) { + if (storage != null) { + int y = (storage.getYLocation() >> 4) & 0xf; + dataArray[y] = storage.getData(); + lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; + } + } + } + + return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), + dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); + } + + public synchronized void addChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + this.chunkMap.put(chunk, 0); + } + } + + public synchronized void removeChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? + int flags = this.chunkMap.get(chunk); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(chunk); + } + this.chunkMap.remove(chunk); + } + } + + public synchronized void saveChunks() { + for (Map.Entry entry : this.chunkMap.entrySet()) { + int flags = entry.getValue(); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(entry.getKey()); + } + } + } + + public void updateUndergroundChunks() { + int chunkArrayX = (this.mw.playerXInt >> 4) - 1; + int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; + MwChunk[] chunkArray = new MwChunk[9]; + for (int z = 0; z < 3; z++) { + for (int x = 0; x < 3; x++) { + Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( + chunkArrayX + x, + chunkArrayZ + z + ); + if (!chunk.isEmpty()) { + chunkArray[(z * 3) + x] = copyToMwChunk(chunk); + } + } + } + } + + public void updateSurfaceChunks() { + int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); + MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; + for (int i = 0; i < chunksToUpdate; i++) { + Map.Entry entry = this.chunkMap.getNextEntry(); + if (entry != null) { + // if this chunk is within a certain distance to the player then + // add it to the viewed set + Chunk chunk = entry.getKey(); + + int flags = entry.getValue(); + if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { + flags |= (VISIBLE_FLAG | VIEWED_FLAG); + } else { + flags &= ~VISIBLE_FLAG; + } + entry.setValue(flags); + + if ((flags & VISIBLE_FLAG) != 0) { + chunkArray[i] = copyToMwChunk(chunk); + } else { + chunkArray[i] = null; + } + } + } + + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + public void onTick() { + if (!this.closed) { + if ((this.mw.tickCounter & 0xf) == 0) { + this.updateUndergroundChunks(); + } else { + this.updateSurfaceChunks(); + } + } + } + + public void forceChunks(MwChunk[] chunkArray){ + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + private void addSaveChunkTask(Chunk chunk) { + if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || + (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { + if (!chunk.isEmpty()) { + this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + } + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index de70d62d..ee5988a7 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -1,6 +1,5 @@ package mapwriter.config; -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; import net.minecraftforge.fml.client.config.IConfigElement; diff --git a/src/main/java/mapwriter/config/smallMapModeConfig.java b/src/main/java/mapwriter/config/smallMapModeConfig.java index cd53f170..d9f37bb8 100644 --- a/src/main/java/mapwriter/config/smallMapModeConfig.java +++ b/src/main/java/mapwriter/config/smallMapModeConfig.java @@ -1,38 +1,34 @@ -package mapwriter.config; - -import mapwriter.gui.ModGuiConfig.ModBooleanEntry; -import mapwriter.util.Reference; -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; - -public class smallMapModeConfig extends largeMapModeConfig -{ - public smallMapModeConfig(String configCategory) - { - super(configCategory); - } - - @Override - public void loadConfig() - { - super.loadConfig(); - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); - this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); - } - - @Override - public void setDefaults() - { - this.rotateDef = true; - this.circularDef = true; - this.coordsModeDef = coordsModeStringArray[1]; - this.borderModeDef = true; - this.playerArrowSizeDef = 4; - this.markerSizeDef = 3; - this.heightPercentDef = 30; - this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; - - ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); - } -} +package mapwriter.config; + +import mapwriter.util.Reference; + +public class smallMapModeConfig extends largeMapModeConfig +{ + public smallMapModeConfig(String configCategory) + { + super(configCategory); + } + + @Override + public void loadConfig() + { + super.loadConfig(); + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); + this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); + } + + @Override + public void setDefaults() + { + this.rotateDef = true; + this.circularDef = true; + this.coordsModeDef = coordsModeStringArray[1]; + this.borderModeDef = true; + this.playerArrowSizeDef = 4; + this.markerSizeDef = 3; + this.heightPercentDef = 30; + this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; + + ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); + } +} diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index dfd45e7d..4ac17127 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -11,8 +11,6 @@ import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; -import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent; public class EventHandler { diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index 8142791b..e4f7894e 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -9,9 +9,7 @@ import mapwriter.map.mapmode.MapMode; import mapwriter.map.mapmode.SmallMapMode; -public class MiniMap { - private Mw mw; - +public class MiniMap { public MapMode smallMapMode; public MapMode largeMapMode; public MapMode guiMapMode; @@ -25,8 +23,6 @@ public class MiniMap { private MapRenderer currentMap = null; public MiniMap(Mw mw) { - this.mw = mw; - // map view shared between large and small map modes this.view = new MapView(mw); this.view.setZoomLevel(Config.overlayZoomLevel); diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java index ab82ace1..7f0f7807 100644 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -1,7 +1,6 @@ package mapwriter.map.mapmode; import mapwriter.config.Config; -import mapwriter.util.Reference; public class FullScreenMapMode extends MapMode { diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java index c78d5c43..92470a19 100644 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -1,7 +1,6 @@ package mapwriter.map.mapmode; import mapwriter.config.Config; -import mapwriter.util.Reference; public class LargeMapMode extends MapMode { diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java index 13276515..d0ef1317 100644 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -1,7 +1,6 @@ package mapwriter.map.mapmode; import mapwriter.config.Config; -import mapwriter.util.Reference; public class SmallMapMode extends MapMode { diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index e40afeef..7cae680e 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -77,8 +77,6 @@ public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, i double b = 0.0; for (; y > 0; y--) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int block = blockAndMeta >> 4; - int meta = (blockAndMeta | 0xfff0) ^ 0xfff0; int c1 = bc.getColour(blockAndMeta); int alpha = (c1 >> 24) & 0xff; diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 830cee48..fa9a2dff 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -1,392 +1,388 @@ -package mapwriter.region; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.minecraft.block.Block; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockPos; -import net.minecraft.world.chunk.NibbleArray; -import net.minecraftforge.fml.common.FMLLog; - -import org.apache.logging.log4j.Level; - -public class MwChunk implements IChunk { - public static final int SIZE = 16; - - public final int x; - public final int z; - public final int dimension; - - char[][] dataArray = new char[16][]; - public final byte[][] lightingArray; - public final Map tileentityMap; - - public final byte[] biomeArray; - - public final int maxY; - - public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { - this.x = x; - this.z = z; - this.dimension = dimension; - this.biomeArray = biomeArray; - this.lightingArray = lightingArray; - this.tileentityMap = TileEntityMap; - this.dataArray = data; - int maxY = 0; - for (int y = 0; y < 16; y++) { - if (data[y] != null) { - maxY = (y << 4) + 15; - } - } - this.maxY = maxY; - } - - public String toString() { - return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); - } - - // load from anvil file - public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { - - byte[] biomeArray = null; - byte[][] lsbArray = new byte[16][]; - char[][] data = new char[16][]; - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = new HashMap(); - - DataInputStream dis = null; - RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); - if (!regionFile.isOpen()) { - if (regionFile.exists()) { - regionFile.open(); - } - } - - if (regionFile.isOpen()) { - dis = regionFile.getChunkDataInputStream(x & 31, z & 31); - } - - if (dis != null) { - try { - - //chunk NBT structure: - // - //COMPOUND "" - //COMPOUND "level" - // INT "xPos" - // INT "zPos" - // LONG "LastUpdate" - // BYTE "TerrainPopulated" - // BYTE_ARRAY "Biomes" - // INT_ARRAY "HeightMap" - // LIST(COMPOUND) "Sections" - // BYTE "Y" - // BYTE_ARRAY "Blocks" - // BYTE_ARRAY "Add" - // BYTE_ARRAY "Data" - // BYTE_ARRAY "BlockLight" - // BYTE_ARRAY "SkyLight" - // END - // LIST(COMPOUND) "Entities" - // LIST(COMPOUND) "TileEntities" - // LIST(COMPOUND) "TileTicks" - //END - //END - NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); - NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); - - int xNbt = level.getInteger("xPos"); - int zNbt = level.getInteger("zPos"); - - if ((xNbt != x) || (zNbt != z)) { - RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); - } - - NBTTagList sections = level.getTagList("Sections", 10); - - for (int k = 0; k < sections.tagCount(); ++k) - { - NBTTagCompound section = sections.getCompoundTagAt(k); - int y = section.getByte("Y"); - lsbArray[y & 0xf] = section.getByteArray("Blocks"); - NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); - NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; - - data[y & 0xf] = new char[lsbArray[y].length]; - - for (int l = 0; l < data[y & 0xf].length; ++l) - { - int i1 = l & 15; - int j1 = l >> 8 & 15; - int k1 = l >> 4 & 15; - int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; - data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); - } - } - - biomeArray = level.getByteArray("Biomes"); - - NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); - - if (nbttaglist2 != null) - { - for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) - { - NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); - TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); - if (tileentity != null) - { - TileEntityMap.put(tileentity.getPos(), tileentity); - } - } - } - - - } catch (IOException e) { - RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); - } finally { - try { dis.close(); } - catch (IOException e) { - RegionManager.logError("MwChunk.read: %s while closing input stream", e); - } - } - //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); - } else { - //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); - } - - return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); - } - - public boolean isEmpty() { - return (this.maxY <= 0); - } - - public int getBiome(int x, int z) { - return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; - } - - public int getLightValue(int x, int y, int z) { - //int yi = (y >> 4) & 0xf; - //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; - - //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); - return 15; - } - - public int getMaxY() { - return this.maxY; - } - - public int getBlockAndMetadata(int x, int y, int z) { - int yi = (y >> 4) & 0xf; - int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - int lsb = 0; - int msb = 0; - int meta = 0; - - BlockPos pos = new BlockPos(x,y,z); - - char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; - - //check if the block has a tileentity if so use the blockdata in the tileentity - //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) - if (this.tileentityMap.containsKey(pos)) - { - - TileEntity value = (TileEntity)this.tileentityMap.get(pos); - NBTTagCompound tag = new NBTTagCompound(); - value.writeToNBT(tag); - int id = 0; - - if (tag.getString("id") == "savedMultipart") - { - String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); - int end = material.indexOf("_"); - - //block with metadata - if (end != -1) - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); - - lsb = (id & 255); - - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - meta = Integer.parseInt(material.substring(end+1)); - } - //block without metadata - else - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); - - lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - } - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - else if (tag.getString("id") =="TileEntityCarpentersBlock") - { - NBTTagList TagList = tag.getTagList("cbAttrList", 10); - String sid = TagList.getCompoundTagAt(0).getString("id"); - String smeta = TagList.getCompoundTagAt(0).getString("Damage"); - if (sid != "") - { - id = Integer.parseInt(sid.substring(0, sid.length()-1)); - - lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - if (smeta != "") - { - meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); - } - - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - } - } - - //return ((offset & 1) == 1) ? - // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : - return (int)data; - } - - //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data - private NBTTagCompound writeChunkToNBT() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound.setTag("Level", nbttagcompound1); - - nbttagcompound1.setInteger("xPos", this.x); - nbttagcompound1.setInteger("zPos", this.z); - - NBTTagList nbttaglist = new NBTTagList(); - - int i = 16; - NBTTagCompound nbttagcompound2; - - for (int y = 0; y < this.dataArray.length; y++) - { - if (this.dataArray[y] != null) - { - byte[] abyte = new byte[this.dataArray[y].length]; - NibbleArray nibblearray = new NibbleArray(); - NibbleArray nibblearray1 = null; - - for (int k = 0; k < this.dataArray[y].length; ++k) - { - char c0 = this.dataArray[y][k]; - int l = k & 15; - int i1 = k >> 8 & 15; - int j1 = k >> 4 & 15; - - if (c0 >> 12 != 0) - { - if (nibblearray1 == null) - { - nibblearray1 = new NibbleArray(); - } - - nibblearray1.set(l, i1, j1, c0 >> 12); - } - - abyte[k] = (byte)(c0 >> 4 & 255); - nibblearray.set(l, i1, j1, c0 & 15); - } - - - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Y", (byte)y); - nbttagcompound2.setByteArray("Blocks", abyte); - - if (nibblearray1 != null) - { - nbttagcompound2.setByteArray("Add", nibblearray1.getData()); - } - - nbttagcompound2.setByteArray("Data", nibblearray.getData()); - nbttaglist.appendTag(nbttagcompound2); - } - - nbttagcompound1.setTag("Sections", nbttaglist); - } - nbttagcompound1.setByteArray("Biomes", this.biomeArray); - - NBTTagList nbttaglist2 = new NBTTagList(); - Iterator iterator1; - - NBTTagList nbttaglist3 = new NBTTagList(); - - iterator1 = this.tileentityMap.values().iterator(); - - while (iterator1.hasNext()) - { - TileEntity tileentity = (TileEntity)iterator1.next(); - nbttagcompound2 = new NBTTagCompound(); - try { - tileentity.writeToNBT(nbttagcompound2); - nbttaglist3.appendTag(nbttagcompound2); - } - catch (Exception e) - { - FMLLog.log(Level.ERROR, e, - "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", - tileentity.getClass().getName()); - } - } - nbttagcompound1.setTag("TileEntities", nbttaglist3); - - return nbttagcompound; - } - - public synchronized boolean write(RegionFileCache regionFileCache) { - boolean error = false; - RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); - if (!regionFile.isOpen()) { - error = regionFile.open(); - } - if (!error) { - DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); - if (dos != null) { - //Nbt chunkNbt = this.getNbt(); - try { - //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); - //chunkNbt.writeElement(dos); - //use minecraft build in save tool for saving the Anvil Data - CompressedStreamTools.write(writeChunkToNBT(), dos); - } catch (IOException e) { - RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); - error = true; - } finally { - try { dos.close(); } - catch (IOException e) { - RegionManager.logError("%s while closing chunk data output stream", e); - } - } - } else { - RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); - } - } else { - RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); - } - - return error; - } -} +package mapwriter.region; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import net.minecraft.block.Block; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.NibbleArray; +import net.minecraftforge.fml.common.FMLLog; + +import org.apache.logging.log4j.Level; + +public class MwChunk implements IChunk { + public static final int SIZE = 16; + + public final int x; + public final int z; + public final int dimension; + + char[][] dataArray = new char[16][]; + public final byte[][] lightingArray; + public final Map tileentityMap; + + public final byte[] biomeArray; + + public final int maxY; + + public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { + this.x = x; + this.z = z; + this.dimension = dimension; + this.biomeArray = biomeArray; + this.lightingArray = lightingArray; + this.tileentityMap = TileEntityMap; + this.dataArray = data; + int maxY = 0; + for (int y = 0; y < 16; y++) { + if (data[y] != null) { + maxY = (y << 4) + 15; + } + } + this.maxY = maxY; + } + + public String toString() { + return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); + } + + // load from anvil file + public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { + + byte[] biomeArray = null; + byte[][] lsbArray = new byte[16][]; + char[][] data = new char[16][]; + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = new HashMap(); + + DataInputStream dis = null; + RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); + if (!regionFile.isOpen()) { + if (regionFile.exists()) { + regionFile.open(); + } + } + + if (regionFile.isOpen()) { + dis = regionFile.getChunkDataInputStream(x & 31, z & 31); + } + + if (dis != null) { + try { + + //chunk NBT structure: + // + //COMPOUND "" + //COMPOUND "level" + // INT "xPos" + // INT "zPos" + // LONG "LastUpdate" + // BYTE "TerrainPopulated" + // BYTE_ARRAY "Biomes" + // INT_ARRAY "HeightMap" + // LIST(COMPOUND) "Sections" + // BYTE "Y" + // BYTE_ARRAY "Blocks" + // BYTE_ARRAY "Add" + // BYTE_ARRAY "Data" + // BYTE_ARRAY "BlockLight" + // BYTE_ARRAY "SkyLight" + // END + // LIST(COMPOUND) "Entities" + // LIST(COMPOUND) "TileEntities" + // LIST(COMPOUND) "TileTicks" + //END + //END + NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); + NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); + + int xNbt = level.getInteger("xPos"); + int zNbt = level.getInteger("zPos"); + + if ((xNbt != x) || (zNbt != z)) { + RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); + } + + NBTTagList sections = level.getTagList("Sections", 10); + + for (int k = 0; k < sections.tagCount(); ++k) + { + NBTTagCompound section = sections.getCompoundTagAt(k); + int y = section.getByte("Y"); + lsbArray[y & 0xf] = section.getByteArray("Blocks"); + NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); + NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; + + data[y & 0xf] = new char[lsbArray[y].length]; + + for (int l = 0; l < data[y & 0xf].length; ++l) + { + int i1 = l & 15; + int j1 = l >> 8 & 15; + int k1 = l >> 4 & 15; + int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; + data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); + } + } + + biomeArray = level.getByteArray("Biomes"); + + NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); + + if (nbttaglist2 != null) + { + for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) + { + NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); + TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); + if (tileentity != null) + { + TileEntityMap.put(tileentity.getPos(), tileentity); + } + } + } + + + } catch (IOException e) { + RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); + } finally { + try { dis.close(); } + catch (IOException e) { + RegionManager.logError("MwChunk.read: %s while closing input stream", e); + } + } + //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); + } else { + //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); + } + + return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); + } + + public boolean isEmpty() { + return (this.maxY <= 0); + } + + public int getBiome(int x, int z) { + return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; + } + + public int getLightValue(int x, int y, int z) { + //int yi = (y >> 4) & 0xf; + //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; + + //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); + return 15; + } + + public int getMaxY() { + return this.maxY; + } + + public int getBlockAndMetadata(int x, int y, int z) { + int yi = (y >> 4) & 0xf; + int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + int lsb = 0; + int msb = 0; + int meta = 0; + + BlockPos pos = new BlockPos(x,y,z); + + char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; + + //check if the block has a tileentity if so use the blockdata in the tileentity + //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) + if (this.tileentityMap.containsKey(pos)) + { + + TileEntity value = (TileEntity)this.tileentityMap.get(pos); + NBTTagCompound tag = new NBTTagCompound(); + value.writeToNBT(tag); + int id = 0; + + if (tag.getString("id") == "savedMultipart") + { + String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); + int end = material.indexOf("_"); + + //block with metadata + if (end != -1) + { + id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); + + lsb = (id & 255); + + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + + meta = Integer.parseInt(material.substring(end+1)); + } + //block without metadata + else + { + id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); + + lsb = (id & 255); + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + } + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } + else if (tag.getString("id") =="TileEntityCarpentersBlock") + { + NBTTagList TagList = tag.getTagList("cbAttrList", 10); + String sid = TagList.getCompoundTagAt(0).getString("id"); + String smeta = TagList.getCompoundTagAt(0).getString("Damage"); + if (sid != "") + { + id = Integer.parseInt(sid.substring(0, sid.length()-1)); + + lsb = (id & 255); + if (id > 255){msb = (id & 3840) >> 8;} + else {msb = 0;} + + if (smeta != "") + { + meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); + } + + data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } + } + } + + //return ((offset & 1) == 1) ? + // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : + return (int)data; + } + + //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data + private NBTTagCompound writeChunkToNBT() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound.setTag("Level", nbttagcompound1); + + nbttagcompound1.setInteger("xPos", this.x); + nbttagcompound1.setInteger("zPos", this.z); + + NBTTagList nbttaglist = new NBTTagList(); + + NBTTagCompound nbttagcompound2; + + for (int y = 0; y < this.dataArray.length; y++) + { + if (this.dataArray[y] != null) + { + byte[] abyte = new byte[this.dataArray[y].length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < this.dataArray[y].length; ++k) + { + char c0 = this.dataArray[y][k]; + int l = k & 15; + int i1 = k >> 8 & 15; + int j1 = k >> 4 & 15; + + if (c0 >> 12 != 0) + { + if (nibblearray1 == null) + { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte)(c0 >> 4 & 255); + nibblearray.set(l, i1, j1, c0 & 15); + } + + + nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Y", (byte)y); + nbttagcompound2.setByteArray("Blocks", abyte); + + if (nibblearray1 != null) + { + nbttagcompound2.setByteArray("Add", nibblearray1.getData()); + } + + nbttagcompound2.setByteArray("Data", nibblearray.getData()); + nbttaglist.appendTag(nbttagcompound2); + } + + nbttagcompound1.setTag("Sections", nbttaglist); + } + nbttagcompound1.setByteArray("Biomes", this.biomeArray); + + NBTTagList nbttaglist3 = new NBTTagList(); + + Iterator iterator1 = this.tileentityMap.values().iterator(); + + while (iterator1.hasNext()) + { + TileEntity tileentity = (TileEntity)iterator1.next(); + nbttagcompound2 = new NBTTagCompound(); + try { + tileentity.writeToNBT(nbttagcompound2); + nbttaglist3.appendTag(nbttagcompound2); + } + catch (Exception e) + { + FMLLog.log(Level.ERROR, e, + "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", + tileentity.getClass().getName()); + } + } + nbttagcompound1.setTag("TileEntities", nbttaglist3); + + return nbttagcompound; + } + + public synchronized boolean write(RegionFileCache regionFileCache) { + boolean error = false; + RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); + if (!regionFile.isOpen()) { + error = regionFile.open(); + } + if (!error) { + DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); + if (dos != null) { + //Nbt chunkNbt = this.getNbt(); + try { + //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); + //chunkNbt.writeElement(dos); + //use minecraft build in save tool for saving the Anvil Data + CompressedStreamTools.write(writeChunkToNBT(), dos); + } catch (IOException e) { + RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); + error = true; + } finally { + try { dos.close(); } + catch (IOException e) { + RegionManager.logError("%s while closing chunk data output stream", e); + } + } + } else { + RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); + } + } else { + RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/util/Logging.java b/src/main/java/mapwriter/util/Logging.java index 4ce854b5..c509d305 100644 --- a/src/main/java/mapwriter/util/Logging.java +++ b/src/main/java/mapwriter/util/Logging.java @@ -1,7 +1,5 @@ package mapwriter.util; -import java.util.regex.Pattern; - import mapwriter.forge.MwForge; public class Logging diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index c2ebb161..bc11898d 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,152 +1,227 @@ -package mapwriter.util; - -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -import mapwriter.config.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return Reference.patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - //send an ingame chat message and console log - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - Logging.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } - - public static String getWorldName() { - String worldName; - - if (Minecraft.getMinecraft().isIntegratedServerRunning()) - { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - else - { - worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; - if (!Config.portNumberInWorldNameEnabled) - { - worldName = worldName.substring(0, worldName.indexOf(":")); - } - else - { - if(worldName.indexOf(":")==-1){//standard port is missing. Adding it - worldName += "_25565"; - } else { - worldName = worldName.replace(":", "_"); - } - } - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } -} +package mapwriter.util; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mapwriter.config.Config; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + //send an ingame chat message and console log + public static void printBoth(String msg) { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } + + public static String getWorldName() { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + if(worldName.indexOf(":")==-1){//standard port is missing. Adding it + worldName += "_25565"; + } else { + worldName = worldName.replace(":", "_"); + } + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } + + /* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * @since 4.37 + * @author Jaroslav Tulach + */ + /* + * Create a typesafe copy of a raw map. + * @param rawMap an unchecked map + * @param keyType the desired supertype of the keys + * @param valueType the desired supertype of the values + * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, + * false to skip over such map entries (warnings may be logged) + * @return a typed map guaranteed to contain only keys and values assignable + * to the named types (or they may be null) + * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true + */ + @SuppressWarnings("rawtypes") + public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { + Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); + Iterator it = rawMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry e = (Map.Entry) it.next(); + try { + m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); + } catch (ClassCastException x) { + if (strict) { + throw x; + } else { + System.out.println("not assignable"); + } + } + } + return m2; + } +} From 8dd128f5701dc711b00bd5920be3343f86f21c65 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 29 Jun 2015 17:19:39 +0200 Subject: [PATCH 048/109] fixes The large map render is drawn on top of the items in your inventory bar --- src/main/java/mapwriter/util/Render.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index 8a41714e..aa30cb39 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -20,7 +20,7 @@ */ public class Render { - public static double zDepth = 0.0D; + public static double zDepth = 200.0D; public static final double circleSteps = 30.0; public static void setColourWithAlphaPercent(int colour, int alphaPercent) { @@ -300,7 +300,7 @@ public static void setCircularStencil(double x, double y, double r) { GL11.glEnable(GL11.GL_DEPTH_TEST); // disable drawing to the color buffer. // circle will only be drawn to depth buffer. - GL11.glColorMask(false, false, false, false); + GlStateManager.colorMask(false, false, false, false); // enable writing to depth buffer GlStateManager.depthMask(true); @@ -314,8 +314,8 @@ public static void setCircularStencil(double x, double y, double r) { // set it up by default. // clear depth buffer to z = 3000.0 - //GL11.glClearDepth(3000.0); - //GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + //GlStateManager.clearDepth(3000.0); + //GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT); // always write to depth buffer GlStateManager.depthFunc(GL11.GL_ALWAYS); @@ -324,10 +324,10 @@ public static void setCircularStencil(double x, double y, double r) { Render.setColour(0xffffffff); Render.zDepth = 1000.0; Render.drawCircle(x, y, r); - Render.zDepth = 0.0; + Render.zDepth = 200.0; // re-enable drawing to colour buffer - GL11.glColorMask(true, true, true, true); + GlStateManager.colorMask(true, true, true, true); // disable drawing to depth buffer GlStateManager.depthMask(false); // only draw pixels with z values that are greater From 1e8f18954e3631e5c718fb71aac1d14aaf558c26 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 29 Jun 2015 19:23:57 +0200 Subject: [PATCH 049/109] loads of minor fixes Fixed some standing fixme's removed auto generated method todo's fix for strings not being drawn on fullscreen map after changing the zdepth. zdepth is 200 when map is circular mode and 0 otherwise --- src/main/java/mapwriter/BlockColourGen.java | 14 +++++++++++--- .../java/mapwriter/gui/ModGuiFactoryHandler.java | 4 ---- .../java/mapwriter/overlay/OverlayChecker.java | 9 ++------- src/main/java/mapwriter/overlay/OverlayGrid.java | 7 +------ src/main/java/mapwriter/overlay/OverlaySlime.java | 6 ------ src/main/java/mapwriter/util/Render.java | 5 ++++- 6 files changed, 18 insertions(+), 27 deletions(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 22d5dd9b..de7e3342 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -10,6 +10,9 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.BlockPos; +import net.minecraft.util.MathHelper; +import net.minecraft.world.ColorizerFoliage; +import net.minecraft.world.ColorizerGrass; import net.minecraft.world.biome.BiomeGenBase; // Static class to generate BlockColours. @@ -81,8 +84,14 @@ private static void genBiomeColours(BlockColours bc) { for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { if (BiomeGenBase.getBiomeGenArray()[i] != null) { bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); - bc.setBiomeGrassShading(i, BiomeGenBase.getBiomeGenArray()[i].getGrassColorAtPos(new BlockPos(0, 0, 0)) & 0xffffff); //FIXME 0,0,0? - bc.setBiomeFoliageShading(i, BiomeGenBase.getBiomeGenArray()[i].getFoliageColorAtPos(new BlockPos(0, 0, 0)) & 0xffffff); //FIXME 0,0,0? + + double temp = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].temperature, 0.0F, 1.0F); + double rain = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].rainfall, 0.0F, 1.0F); + int grasscolor = ColorizerGrass.getGrassColor(temp, rain); + int foliagecolor = ColorizerFoliage.getFoliageColor(temp, rain); + + bc.setBiomeGrassShading(i, grasscolor & 0xffffff); + bc.setBiomeFoliageShading(i, foliagecolor & 0xffffff); } else { bc.setBiomeWaterShading(i, 0xffffff); bc.setBiomeGrassShading(i, 0xffffff); @@ -120,7 +129,6 @@ public static void genBlockColours(BlockColours bc) { int b_count = 0; int s_count = 0; - //for (int blockID = 0; blockID < 4096; blockID++) { //TODO: replace hardcoded 4096 with actual registry size for (Object oblock : Block.blockRegistry){ Block block = (Block)oblock; int blockID = Block.getIdFromBlock(block); diff --git a/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java index 048c4c8b..35f3e8af 100644 --- a/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java +++ b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java @@ -11,26 +11,22 @@ public class ModGuiFactoryHandler implements IModGuiFactory @Override public void initialize(Minecraft minecraftInstance) { - // TODO Auto-generated method stub } @Override public Class mainConfigGuiClass() { - // TODO Auto-generated method stub return ModGuiConfig.class; } @Override public Set runtimeGuiCategories() { - // TODO Auto-generated method stub return null; } @Override public RuntimeOptionGuiHandler getHandlerFor( RuntimeOptionCategoryElement element) { - // TODO Auto-generated method stub return null; } diff --git a/src/main/java/mapwriter/overlay/OverlayChecker.java b/src/main/java/mapwriter/overlay/OverlayChecker.java index 62c6847e..8816a6ee 100644 --- a/src/main/java/mapwriter/overlay/OverlayChecker.java +++ b/src/main/java/mapwriter/overlay/OverlayChecker.java @@ -78,37 +78,32 @@ public void onDimensionChanged(int dimension, MapView mapview) { } @Override public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub - + } @Override public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub } @Override public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub + return false; } diff --git a/src/main/java/mapwriter/overlay/OverlayGrid.java b/src/main/java/mapwriter/overlay/OverlayGrid.java index 68ae31bf..f8556349 100644 --- a/src/main/java/mapwriter/overlay/OverlayGrid.java +++ b/src/main/java/mapwriter/overlay/OverlayGrid.java @@ -72,37 +72,32 @@ public void onDimensionChanged(int dimension, MapView mapview) { } @Override public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub } @Override public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub } @Override public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub + return false; } diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java index 778843d2..a284391c 100644 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -120,37 +120,31 @@ public void onDimensionChanged(int dimension, MapView mapview) { } @Override public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub } @Override public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub } @Override public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub } @Override public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub return false; } diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index aa30cb39..d82b6be6 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -20,7 +20,7 @@ */ public class Render { - public static double zDepth = 200.0D; + public static double zDepth = 0.0D; public static final double circleSteps = 30.0; public static void setColourWithAlphaPercent(int colour, int alphaPercent) { @@ -342,6 +342,9 @@ public static void disableStencil() { GlStateManager.depthFunc(GL11.GL_LEQUAL); GlStateManager.disableDepth(); GL11.glDisable(GL11.GL_DEPTH_TEST); + + //set the zDepth to 0 to make sure there arent any problems drawing other things when circular map isnt drawn + Render.zDepth = 0.0; } // A better implementation of a circular stencil using the stencil buffer From 443afdbc9a5bdb2dc52915d93ea4714188efb8aa Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 7 Jul 2015 18:18:25 +0200 Subject: [PATCH 050/109] new way of showing hight in the map (using atan instead of a power) --- src/main/java/mapwriter/region/ChunkRender.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 7cae680e..0e696d5d 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -36,16 +36,17 @@ public static double getHeightShading(int height, int heightW, int heightN) { double heightDiffFactor = 0.0; if (samples > 0) { - heightDiffFactor = (double) heightDiff / ((double) samples * 255.0); + heightDiffFactor = (double) heightDiff / ((double) samples); } // emphasize small differences in height, but as the difference in height increases, // don't increase so much // TODO: probably more accurate to use atan here rather than a fractional // exponent. - return (heightDiffFactor >= 0.0) ? - Math.pow(heightDiffFactor, brightenExponent) * brightenAmplitude : - -Math.pow(-heightDiffFactor, darkenExponent) * darkenAmplitude; + return Math.atan(heightDiffFactor) *0.5; + //return Math.atan(heightDiffFactor) *0.4; + //return Math.atan(heightDiffFactor); + //return (heightDiffFactor >= 0.0) ? Math.pow(heightDiffFactor, brightenExponent) * brightenAmplitude : -Math.pow(-heightDiffFactor, darkenExponent) * darkenAmplitude; } // calculate the colour of a pixel by alpha blending the colour of each block From 91efb0076731cca1ff12ce2c46795bdc8133d5be Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 12 Jul 2015 22:55:09 +0200 Subject: [PATCH 051/109] Made the blockcolour generation use the blocknames, removes the need to load the blockcolours when opening a world. added a option to switch between realistic map rendering and old way inserted the crash prevention from the 1.7.10 version to be sure. --- build.properties | 2 +- src/main/java/mapwriter/BlockColourGen.java | 187 +++--- src/main/java/mapwriter/Mw.java | 2 - src/main/java/mapwriter/config/Config.java | 3 + .../config/ConfigurationHandler.java | 2 + .../java/mapwriter/region/BlockColours.java | 578 +++++++++++------- .../java/mapwriter/region/ChunkRender.java | 180 +++--- src/main/java/mapwriter/region/MwChunk.java | 565 +++++++++-------- src/main/java/mapwriter/util/Texture.java | 15 +- .../assets/mapwriter/lang/en_US.lang | 2 + 10 files changed, 855 insertions(+), 681 deletions(-) diff --git a/build.properties b/build.properties index 7f3b8fc4..8f8bddb8 100644 --- a/build.properties +++ b/build.properties @@ -3,4 +3,4 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 -mod_version=2.2.5 +mod_version=2.2.7 diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index de7e3342..19cc7509 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -6,10 +6,10 @@ import mapwriter.util.Render; import mapwriter.util.Texture; import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.ColorizerGrass; @@ -22,74 +22,53 @@ // must not have any interaction after it is generated. public class BlockColourGen { - - private static int getIconMapColour(TextureAtlasSprite icon, Texture terrainTexture) { - // flipped icons have the U and V coords reversed (minU > maxU, minV > maxV). - // thanks go to taelnia for fixing this. - int iconX = (int) Math.round(((float) terrainTexture.w) * Math.min(icon.getMinU(), icon.getMaxU())); - int iconY = (int) Math.round(((float) terrainTexture.h) * Math.min(icon.getMinV(), icon.getMaxV())); - int iconWidth = (int) Math.round(((float) terrainTexture.w) * Math.abs(icon.getMaxU() - icon.getMinU())); - int iconHeight = (int) Math.round(((float) terrainTexture.h) * Math.abs(icon.getMaxV() - icon.getMinV())); - + + private static int getIconMapColour(TextureAtlasSprite icon, + Texture terrainTexture) { + // flipped icons have the U and V coords reversed (minU > maxU, minV > + // maxV). + // thanks go to taelnia for fixing this. + int iconX = (int) Math.round(((float) terrainTexture.w) + * Math.min(icon.getMinU(), icon.getMaxU())); + int iconY = (int) Math.round(((float) terrainTexture.h) + * Math.min(icon.getMinV(), icon.getMaxV())); + int iconWidth = (int) Math.round(((float) terrainTexture.w) + * Math.abs(icon.getMaxU() - icon.getMinU())); + int iconHeight = (int) Math.round(((float) terrainTexture.h) + * Math.abs(icon.getMaxV() - icon.getMinV())); + int[] pixels = new int[iconWidth * iconHeight]; - - //MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); - - terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, iconWidth); - - // need to use custom averaging routine rather than scaling down to one pixel to + + // MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); + + terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, + iconWidth, icon); + + // need to use custom averaging routine rather than scaling down to one + // pixel to // stop transparent pixel colours being included in the average. return Render.getAverageColourOfArray(pixels); } - - private static int adjustBlockColourFromType(BlockColours bc, int blockAndMeta, int blockColour) { - // for normal blocks multiply the block colour by the render colour. - // for other blocks the block colour will be multiplied by the biome colour. - int blockid = blockAndMeta >> 4; - Block block = (Block) Block.blockRegistry.getObjectById(blockid); - BlockType blockType = bc.getBlockType(blockAndMeta); - switch (blockType) { - - case OPAQUE: - blockColour |= 0xff000000; - case NORMAL: - // fix crash when mods don't implement getRenderColor for all - // block meta values. - try { - int renderColour = block.getRenderColor(block.getStateFromMeta(blockAndMeta & 0xf)); - if (renderColour != 0xffffff) { - blockColour = Render.multiplyColours(blockColour, 0xff000000 | renderColour); - } - } catch (RuntimeException e) { - // do nothing - } - break; - case LEAVES: - // leaves look weird on the map if they are not opaque. - // they also look too dark if the render colour is applied. - blockColour |= 0xff000000; - break; - case GRASS: - blockColour = 0xff9b9b9b; - default: - break; - } - return blockColour; - } - + private static void genBiomeColours(BlockColours bc) { // generate array of foliage, grass, and water colour multipliers // for each biome. - + for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { if (BiomeGenBase.getBiomeGenArray()[i] != null) { - bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); - - double temp = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].temperature, 0.0F, 1.0F); - double rain = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].rainfall, 0.0F, 1.0F); + bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i] + .getWaterColorMultiplier() & 0xffffff); + + double temp = MathHelper.clamp_float( + BiomeGenBase.getBiomeGenArray()[i].temperature, 0.0F, + 1.0F); + double rain = MathHelper + .clamp_float( + BiomeGenBase.getBiomeGenArray()[i].rainfall, + 0.0F, 1.0F); int grasscolor = ColorizerGrass.getGrassColor(temp, rain); int foliagecolor = ColorizerFoliage.getFoliageColor(temp, rain); - + bc.setBiomeGrassShading(i, grasscolor & 0xffffff); bc.setBiomeFoliageShading(i, foliagecolor & 0xffffff); } else { @@ -99,27 +78,28 @@ private static void genBiomeColours(BlockColours bc) { } } } - + public static void genBlockColours(BlockColours bc) { - + Logging.log("generating block map colours from textures"); // copy terrain texture to MwRender pixel bytebuffer - + // bind the terrain texture - //Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); + // Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); // get the bound texture id - //int terrainTextureId = Render.getBoundTextureId(); - - int terrainTextureId = Minecraft.getMinecraft().renderEngine.getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); - + // int terrainTextureId = Render.getBoundTextureId(); + + int terrainTextureId = Minecraft.getMinecraft().renderEngine + .getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); + // create texture object from the currently bound GL texture if (terrainTextureId == 0) { Logging.log("error: could get terrain texture ID"); return; } Texture terrainTexture = new Texture(terrainTextureId); - + double u1Last = 0; double u2Last = 0; double v1Last = 0; @@ -129,46 +109,56 @@ public static void genBlockColours(BlockColours bc) { int b_count = 0; int s_count = 0; - for (Object oblock : Block.blockRegistry){ - Block block = (Block)oblock; + for (Object oblock : Block.blockRegistry) { + Block block = (Block) oblock; int blockID = Block.getIdFromBlock(block); - + if (blockID == 0) { + continue; + } for (int dv = 0; dv < 16; dv++) { - + int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); int blockColour = 0; - + if (block != null) { - + TextureAtlasSprite icon = null; try { - icon = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(block.getStateFromMeta(dv)); + icon = Minecraft.getMinecraft() + .getBlockRendererDispatcher() + .getBlockModelShapes() + .getTexture(block.getStateFromMeta(dv)); } catch (Exception e) { - //MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", blockID, dv); - //e.printStackTrace(); + // MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", + // blockID, dv); + // e.printStackTrace(); e_count++; } - + if (icon != null) { double u1 = icon.getMinU(); double u2 = icon.getMaxU(); double v1 = icon.getMinV(); double v2 = icon.getMaxV(); - - if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) && (v2 == v2Last)) { + + if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) + && (v2 == v2Last)) { blockColour = blockColourLast; s_count++; } else { blockColour = getIconMapColour(icon, terrainTexture); + // request icon with meta 16, carpenterblocks uses + // this method to get the real texture + // this makes the carpenterblocks render as brown + // blocks on the map + // FIXME:check how carpenterblocks fixes this + // if (blockColour == 0) + // { + // icon = block.getIcon(1, 16); + // blockColour = getIconMapColour(icon, + // terrainTexture); + // } - //request icon with meta 16, carpenterblocks uses this method to get the real texture - //this makes the carpenterblocks render as brown blocks on the map - //FIXME:check how carpenterblocks fixes this - //if (blockColour == 0) - //{ - // icon = block.getIcon(1, 16); - // blockColour = getIconMapColour(icon, terrainTexture); - //} u1Last = u1; u2Last = u2; v1Last = v1; @@ -176,27 +166,16 @@ public static void genBlockColours(BlockColours bc) { blockColourLast = blockColour; b_count++; } - //if (dv == 0) - // MwUtil.log("block %03x:%x colour = %08x", blockID, dv, blockColour); } - - // doesn't work as some leaves blocks aren't rendered using the biome - // foliage colour - //try { - // if (block.isLeaves(null, 0, 0, 0)) { - // bc.setBlockType(blockAndMeta, BlockType.LEAVES); - // } - //} catch (NullPointerException e) { - //} - - blockColour = adjustBlockColourFromType(bc, blockAndMeta, blockColour); } - bc.setColour(blockAndMeta, blockColour); + bc.setColour(block.delegate.name(), String.valueOf(dv), + blockColour); } } - - Logging.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); - + + Logging.log("processed %d block textures, %d skipped, %d exceptions", + b_count, s_count, e_count); + genBiomeColours(bc); } } diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 93722e0a..ee00b542 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -220,8 +220,6 @@ public void reloadBlockColours() { } else { // generate block colours from current texture pack Logging.logInfo("generating block colours"); - // block type overrides need to be loaded before the block colours are generated - this.loadBlockColourOverrides(bc); BlockColourGen.genBlockColours(bc); // load overrides again to override block and biome colours this.loadBlockColourOverrides(bc); diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 8c9c5822..1984c08b 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -46,6 +46,9 @@ public class Config { public static boolean regionFileOutputEnabledMP = regionFileOutputEnabledMPDef; public static String backgroundTextureModeDef = backgroundModeStringArray[0]; public static String backgroundTextureMode = backgroundTextureModeDef; + public static boolean moreRealisticMapDef = false; + public static boolean moreRealisticMap = moreRealisticMapDef; + //World configuration Options public static int overlayModeIndex = 0; diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 9b86e7e0..401d1b0b 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -47,6 +47,8 @@ public static void loadConfig() Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "mw.config.overlayModeIndex"); Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); + Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); + Config.fullScreenMap.loadConfig(); Config.largeMap.loadConfig(); Config.smallMap.loadConfig(); diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 0a32a371..3905105b 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -6,109 +6,150 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; +import mapwriter.util.Render; +import net.minecraft.block.Block; + public class BlockColours { - + public static final int MAX_BLOCKS = 4096; public static final int MAX_META = 16; public static final int MAX_BIOMES = 256; - + public static final String biomeSectionString = "[biomes]"; public static final String blockSectionString = "[blocks]"; - - private int[] bcArray = new int[MAX_BLOCKS * MAX_META]; + + // private int[] bcArray = new int[MAX_BLOCKS * MAX_META]; private int[] waterMultiplierArray = new int[MAX_BIOMES]; private int[] grassMultiplierArray = new int[MAX_BIOMES]; private int[] foliageMultiplierArray = new int[MAX_BIOMES]; - + private LinkedHashMap bcMap = new LinkedHashMap(); + private LinkedHashMap bcOverrideMap = new LinkedHashMap(); + public enum BlockType { - NORMAL, - GRASS, - LEAVES, - FOLIAGE, - WATER, - OPAQUE - } - - private BlockType[] blockTypeArray = new BlockType[MAX_BLOCKS * MAX_META]; - + NORMAL, GRASS, LEAVES, FOLIAGE, WATER, OPAQUE + } + public BlockColours() { - Arrays.fill(this.bcArray, 0); Arrays.fill(this.waterMultiplierArray, 0xffffff); Arrays.fill(this.grassMultiplierArray, 0xffffff); Arrays.fill(this.foliageMultiplierArray, 0xffffff); - Arrays.fill(this.blockTypeArray, BlockType.NORMAL); } - - public int getColour(int blockAndMeta) { - return this.bcArray[blockAndMeta & 0xffff]; + + public String CombineBlockMeta(String BlockName, int meta) { + return BlockName + " " + meta; } - - public void setColour(int blockAndMeta, int colour) { - this.bcArray[blockAndMeta & 0xffff] = colour; + + public String CombineBlockMeta(String BlockName, String meta) { + return BlockName + " " + meta; } - - public int getColour(int blockID, int meta) { - return this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)]; + + public int getColour(String BlockName, int meta) { + String BlockAndMeta = CombineBlockMeta(BlockName, meta); + String BlockAndWildcard = CombineBlockMeta(BlockName, "*"); + + BlockData data = new BlockData(); + + if (this.bcMap.containsKey(BlockAndMeta)) { + data = this.bcMap.get(BlockAndMeta); + } else if (this.bcMap.containsKey(BlockAndWildcard)) { + data = this.bcMap.get(BlockAndWildcard); + } + return data.color; } - - public void setColour(int blockID, int meta, int colour) { - this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)] = colour; + + public int getColour(int BlockAndMeta) { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return getColour(block.delegate.name(), meta); } - + + public void setColour(String BlockName, String meta, int colour) { + String BlockAndMeta = CombineBlockMeta(BlockName, meta); + + if (meta.equals("*")) { + for (int i = 0; i < 16; i++) { + setColour(BlockName, String.valueOf(i), colour); + } + } + + if (this.bcMap.containsKey(BlockAndMeta)) { + BlockData data = this.bcMap.get(BlockAndMeta); + data.color = colour; + } else { + BlockData data = new BlockData(); + data.color = colour; + this.bcMap.put(BlockAndMeta, data); + } + } + private int getGrassColourMultiplier(int biome) { - return (this.grassMultiplierArray != null) && (biome >= 0) && (biome < this.grassMultiplierArray.length) ? - this.grassMultiplierArray[biome] : 0xffffff; + return (this.grassMultiplierArray != null) && (biome >= 0) + && (biome < this.grassMultiplierArray.length) ? this.grassMultiplierArray[biome] + : 0xffffff; } - + private int getWaterColourMultiplier(int biome) { - return (this.waterMultiplierArray != null) && (biome >= 0) && (biome < this.waterMultiplierArray.length) ? - this.waterMultiplierArray[biome] : 0xffffff; + return (this.waterMultiplierArray != null) && (biome >= 0) + && (biome < this.waterMultiplierArray.length) ? this.waterMultiplierArray[biome] + : 0xffffff; } - + private int getFoliageColourMultiplier(int biome) { - return (this.foliageMultiplierArray != null) && (biome >= 0) && (biome < this.foliageMultiplierArray.length) ? - this.foliageMultiplierArray[biome] : 0xffffff; - } - - public int getBiomeColour(int blockAndMeta, int biome) { - blockAndMeta &= 0xffff; - int colourMultiplier; - switch(this.blockTypeArray[blockAndMeta]) { - case GRASS: - colourMultiplier = getGrassColourMultiplier(biome); - break; - case LEAVES: - case FOLIAGE: - colourMultiplier = getFoliageColourMultiplier(biome); - break; - case WATER: - colourMultiplier = getWaterColourMultiplier(biome); - break; - default: - colourMultiplier = 0xffffff; - break; + return (this.foliageMultiplierArray != null) && (biome >= 0) + && (biome < this.foliageMultiplierArray.length) ? this.foliageMultiplierArray[biome] + : 0xffffff; + } + + public int getBiomeColour(String BlockName, int meta, int biome) { + int colourMultiplier = 0xffffff; + + if (this.bcMap.containsKey(CombineBlockMeta(BlockName, meta))) { + switch (this.bcMap.get(CombineBlockMeta(BlockName, meta)).type) { + case GRASS: + colourMultiplier = getGrassColourMultiplier(biome); + break; + case LEAVES: + case FOLIAGE: + colourMultiplier = getFoliageColourMultiplier(biome); + break; + case WATER: + colourMultiplier = getWaterColourMultiplier(biome); + break; + default: + colourMultiplier = 0xffffff; + break; + } } return colourMultiplier; } - + + public int getBiomeColour(int BlockAndMeta, int biome) { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return getBiomeColour(block.delegate.name(), meta, biome); + } + public void setBiomeWaterShading(int biomeID, int colour) { this.waterMultiplierArray[biomeID & 0xff] = colour; } - + public void setBiomeGrassShading(int biomeID, int colour) { this.grassMultiplierArray[biomeID & 0xff] = colour; } - + public void setBiomeFoliageShading(int biomeID, int colour) { this.foliageMultiplierArray[biomeID & 0xff] = colour; } - + private static BlockType getBlockTypeFromString(String typeString) { BlockType blockType = BlockType.NORMAL; if (typeString.equalsIgnoreCase("normal")) { @@ -128,7 +169,7 @@ private static BlockType getBlockTypeFromString(String typeString) { } return blockType; } - + private static String getBlockTypeAsString(BlockType blockType) { String s = "normal"; switch (blockType) { @@ -153,34 +194,99 @@ private static String getBlockTypeAsString(BlockType blockType) { } return s; } - - public BlockType getBlockType(int blockAndMeta) { - return this.blockTypeArray[blockAndMeta & 0xffff]; + + public BlockType getBlockType(String BlockName, int meta) { + String BlockAndMeta = CombineBlockMeta(BlockName, meta); + String BlockAndWildcard = CombineBlockMeta(BlockName, "*"); + + BlockData data = new BlockData(); + + if (this.bcMap.containsKey(BlockAndMeta)) { + data = this.bcMap.get(BlockAndMeta); + } else if (this.bcMap.containsKey(BlockAndWildcard)) { + data = this.bcMap.get(BlockAndWildcard); + } + return data.type; } - - public BlockType getBlockType(int blockId, int meta) { - return this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)]; + + public BlockType getBlockType(int BlockAndMeta) { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return getBlockType(block.delegate.name(), meta); } - - public void setBlockType(int blockId, int meta, BlockType type) { - this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)] = type; + + public void setBlockType(String BlockName, String meta, BlockType type) { + String BlockAndMeta = CombineBlockMeta(BlockName, meta); + + if (meta.equals("*")) { + for (int i = 0; i < 16; i++) { + setBlockType(BlockName, String.valueOf(i), type); + } + return; + } + + if (this.bcMap.containsKey(BlockAndMeta)) { + BlockData data = this.bcMap.get(BlockAndMeta); + data.type = type; + data.color = adjustBlockColourFromType(BlockName, meta, type, + data.color); + } else { + BlockData data = new BlockData(); + data.type = type; + this.bcMap.put(BlockAndMeta, data); + } } - - public void setBlockType(int blockAndMeta, BlockType type) { - this.blockTypeArray[blockAndMeta & 0xffff] = type; + + private static int adjustBlockColourFromType(String BlockName, String meta, + BlockType type, int blockColour) { + // for normal blocks multiply the block colour by the render colour. + // for other blocks the block colour will be multiplied by the biome + // colour. + Block block = Block.getBlockFromName(BlockName); + + switch (type) { + + case OPAQUE: + blockColour |= 0xff000000; + case NORMAL: + // fix crash when mods don't implement getRenderColor for all + // block meta values. + try { + int renderColour = block.getRenderColor(block + .getStateFromMeta(Integer.parseInt(meta) & 0xf)); + if (renderColour != 0xffffff) { + blockColour = Render.multiplyColours(blockColour, + 0xff000000 | renderColour); + } + } catch (RuntimeException e) { + // do nothing + } + break; + case LEAVES: + // leaves look weird on the map if they are not opaque. + // they also look too dark if the render colour is applied. + blockColour |= 0xff000000; + break; + case GRASS: + //the icon returns the dirt texture so hardcode it to the grey undertexture. + blockColour = 0xff9b9b9b; + default: + break; + } + return blockColour; } - + public static int getColourFromString(String s) { return (int) (Long.parseLong(s, 16) & 0xffffffffL); } - + // // Methods for loading block colours from file: // - + // read biome colour multiplier values. // line format is: - // biome + // biome // accepts "*" wildcard for biome id (meaning for all biomes). private void loadBiomeLine(String[] split) { try { @@ -190,79 +296,63 @@ private void loadBiomeLine(String[] split) { startBiomeId = Integer.parseInt(split[1]); endBiomeId = startBiomeId + 1; } - + if ((startBiomeId >= 0) && (startBiomeId < MAX_BIOMES)) { int waterMultiplier = getColourFromString(split[2]) & 0xffffff; int grassMultiplier = getColourFromString(split[3]) & 0xffffff; int foliageMultiplier = getColourFromString(split[4]) & 0xffffff; - + for (int biomeId = startBiomeId; biomeId < endBiomeId; biomeId++) { this.setBiomeWaterShading(biomeId, waterMultiplier); this.setBiomeGrassShading(biomeId, grassMultiplier); this.setBiomeFoliageShading(biomeId, foliageMultiplier); } } else { - RegionManager.logWarning("biome ID '%d' out of range", startBiomeId); + RegionManager.logWarning("biome ID '%d' out of range", + startBiomeId); } - + } catch (NumberFormatException e) { - RegionManager.logWarning("invalid biome colour line '%s %s %s %s %s'", split[0], split[1], split[2], split[3], split[4]); + RegionManager.logWarning( + "invalid biome colour line '%s %s %s %s %s'", split[0], + split[1], split[2], split[3], split[4]); } } - + // read block colour values. // line format is: - // block + // block // the biome id, meta value, and colour code are in hex. - // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or meta values). - private void loadBlockLine(String[] split, boolean isBlockColourLine) { + // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or + // meta values). + private void loadBlockLine(String[] split) { try { - int startBlockId = 0; - int endBlockId = MAX_BLOCKS; - if (!split[1].equals("*")) { - startBlockId = Integer.parseInt(split[1]); - endBlockId = startBlockId + 1; - } - - int startBlockMeta = 0; - int endBlockMeta = MAX_META; - if (!split[2].equals("*")) { - startBlockMeta = Integer.parseInt(split[2]); - endBlockMeta = startBlockMeta + 1; - } - - if ((startBlockId >= 0) && (startBlockId < MAX_BLOCKS) && (startBlockMeta >= 0) && (startBlockMeta < MAX_META)) { - if (isBlockColourLine) { - // block colour line - int colour = getColourFromString(split[3]); - - for (int blockId = startBlockId; blockId < endBlockId; blockId++) { - for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { - this.setColour(blockId, blockMeta, colour); - } - } - } else { - // block type line - BlockType type = getBlockTypeFromString(split[3]); - - for (int blockId = startBlockId; blockId < endBlockId; blockId++) { - for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { - this.setBlockType(blockId, blockMeta, type); - } - } - } - } - + // block colour line + int colour = getColourFromString(split[3]); + this.setColour(split[1], split[2], colour); + + } catch (NumberFormatException e) { + RegionManager.logWarning("invalid block colour line '%s %s %s %s'", + split[0], split[1], split[2], split[3]); + } + } + + private void loadBlockTypeLine(String[] split) { + try { + // block type line + BlockType type = getBlockTypeFromString(split[3]); + this.setBlockType(split[1], split[2], type); } catch (NumberFormatException e) { - RegionManager.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); + RegionManager.logWarning("invalid block colour line '%s %s %s %s'", + split[0], split[1], split[2], split[3]); } } - + public void loadFromFile(File f) { Scanner fin = null; try { fin = new Scanner(new FileReader(f)); - + while (fin.hasNextLine()) { // get next line and remove comments (part of line after #) String line = fin.nextLine().split("#")[0].trim(); @@ -270,46 +360,53 @@ public void loadFromFile(File f) { String[] lineSplit = line.split(" "); if (lineSplit[0].equals("biome") && (lineSplit.length == 5)) { this.loadBiomeLine(lineSplit); - } else if (lineSplit[0].equals("block") && (lineSplit.length == 4)) { - this.loadBlockLine(lineSplit, true); - } else if (lineSplit[0].equals("blocktype") && (lineSplit.length == 4)) { - this.loadBlockLine(lineSplit, false); + } else if (lineSplit[0].equals("block") + && (lineSplit.length == 4)) { + this.loadBlockLine(lineSplit); + } else if (lineSplit[0].equals("blocktype") + && (lineSplit.length == 4)) { + this.loadBlockTypeLine(lineSplit); } else { - RegionManager.logWarning("invalid map colour line '%s'", line); + RegionManager.logWarning( + "invalid map colour line '%s'", line); } } } } catch (IOException e) { - RegionManager.logError("loading block colours: no such file '%s'", f); - + RegionManager.logError("loading block colours: no such file '%s'", + f); + } finally { if (fin != null) { fin.close(); } } } - + // // Methods for saving block colours to file. // - + // save biome colour multipliers to a file. public void saveBiomes(Writer fout) throws IOException { fout.write("biome * ffffff ffffff ffffff\n"); - + for (int biomeId = 0; biomeId < MAX_BIOMES; biomeId++) { int waterMultiplier = this.getWaterColourMultiplier(biomeId) & 0xffffff; int grassMultiplier = this.getGrassColourMultiplier(biomeId) & 0xffffff; int foliageMultiplier = this.getFoliageColourMultiplier(biomeId) & 0xffffff; - + // don't add lines that are covered by the default. - if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) || (foliageMultiplier != 0xffffff)) { - fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, waterMultiplier, grassMultiplier, foliageMultiplier)); + if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) + || (foliageMultiplier != 0xffffff)) { + fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, + waterMultiplier, grassMultiplier, foliageMultiplier)); } } } - - private static String getMostOccurringKey(Map map, String defaultItem) { + + private static String getMostOccurringKey(Map map, + String defaultItem) { // find the most commonly occurring key in a hash map. // only return a key if there is more than 1. int maxCount = 1; @@ -317,25 +414,27 @@ private static String getMostOccurringKey(Map map, String defau for (Entry entry : map.entrySet()) { String key = entry.getKey(); int count = entry.getValue(); - + if (count > maxCount) { maxCount = count; mostOccurringKey = key; } } - + return mostOccurringKey; } - - // to use the least number of lines possible find the most commonly occurring - // item for the 16 different meta values of a block. + + // to use the least number of lines possible find the most commonly + // occurring + // item for the different meta values of a block. // an 'item' is either a block colour or a block type. // the most commonly occurring item is then used as the wildcard entry for // the block, and all non matching items added afterwards. - private static void writeMinimalBlockLines(Writer fout, String lineStart, String[] items, String defaultItem) throws IOException { - + private static void writeMinimalBlockLines(Writer fout, String lineStart, + List items, String defaultItem) throws IOException { + Map frequencyMap = new HashMap(); - + // first count the number of occurrences of each item. for (String item : items) { int count = 0; @@ -344,56 +443,78 @@ private static void writeMinimalBlockLines(Writer fout, String lineStart, String } frequencyMap.put(item, count + 1); } - + // then find the most commonly occurring item. - String mostOccurringItem = getMostOccurringKey(frequencyMap, defaultItem); - + String mostOccurringItem = getMostOccurringKey(frequencyMap, + defaultItem); + // only add a wildcard line if it actually saves lines. if (!mostOccurringItem.equals(defaultItem)) { fout.write(String.format("%s * %s\n", lineStart, mostOccurringItem)); } - + // add lines for items that don't match the wildcard line. - for (int i = 0; i < items.length; i++) { - if (!items[i].equals(mostOccurringItem) && !items[i].equals(defaultItem)) { - fout.write(String.format("%s %d %s\n", lineStart, i, items[i])); + + int meta = 0; + for (String s : items) { + if (!s.equals(mostOccurringItem) && !s.equals(defaultItem)) { + fout.write(String.format("%s %d %s\n", lineStart, meta, s)); } + meta++; } } - + public void saveBlocks(Writer fout) throws IOException { fout.write("block * * 00000000\n"); - - String[] colours = new String[MAX_META]; - - for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { - // build a 16 element list of block colours - for (int meta = 0; meta < MAX_META; meta++) { - colours[meta] = String.format("%08x", this.getColour(blockId, meta)); + + String LastBlock = ""; + List colours = new ArrayList(); + + for (Map.Entry entry : bcMap.entrySet()) { + String[] BlockAndMeta = entry.getKey().split(" "); + String block = BlockAndMeta[0]; + String meta = BlockAndMeta[1]; + + String color = String.format("%08x", entry.getValue().color); + + if (!LastBlock.equals(block) && !LastBlock.isEmpty()) { + String lineStart = String.format("block %s", LastBlock); + writeMinimalBlockLines(fout, lineStart, colours, "00000000"); + + colours.clear(); } - // write a minimal representation to the file - String lineStart = String.format("block %d", blockId); - writeMinimalBlockLines(fout, lineStart, colours, "00000000"); + + colours.add(color); + LastBlock = block; } } - + public void saveBlockTypes(Writer fout) throws IOException { fout.write("blocktype * * normal\n"); - - String[] blockTypes = new String[MAX_META]; - - for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { - // build a 16 element list of block types - for (int meta = 0; meta < MAX_META; meta++) { - BlockType bt = this.getBlockType(blockId, meta); - blockTypes[meta] = getBlockTypeAsString(bt); + + String LastBlock = ""; + List blockTypes = new ArrayList(); + + for (Map.Entry entry : bcMap.entrySet()) { + String[] BlockAndMeta = entry.getKey().split(" "); + String block = BlockAndMeta[0]; + String meta = BlockAndMeta[1]; + + String Type = getBlockTypeAsString(entry.getValue().type); + + if (!LastBlock.equals(block) && !LastBlock.isEmpty()) { + String lineStart = String.format("blocktype %s", LastBlock); + writeMinimalBlockLines(fout, lineStart, blockTypes, + getBlockTypeAsString(BlockType.NORMAL)); + + blockTypes.clear(); } - // write a minimal representation to the file - String lineStart = String.format("blocktype %d", blockId); - writeMinimalBlockLines(fout, lineStart, blockTypes, "normal"); + + blockTypes.add(Type); + LastBlock = block; } } - + // save block colours and biome colour multipliers to a file. public void saveToFile(File f) { Writer fout = null; @@ -402,63 +523,82 @@ public void saveToFile(File f) { this.saveBiomes(fout); this.saveBlockTypes(fout); this.saveBlocks(fout); - + } catch (IOException e) { - RegionManager.logError("saving block colours: could not write to '%s'", f); - + RegionManager.logError( + "saving block colours: could not write to '%s'", f); + } finally { if (fout != null) { try { fout.close(); - } catch (IOException e) {} + } catch (IOException e) { + } } } } - + public static void writeOverridesFile(File f) { Writer fout = null; try { fout = new OutputStreamWriter(new FileOutputStream(f)); - - fout.write( - "block 37 * 60ffff00 # make dandelions more yellow\n" + - "block 38 * 60ff0000 # make roses more red\n" + - "blocktype 2 * grass # grass block\n" + - "blocktype 8 * water # still water block\n" + - "blocktype 9 * water # flowing water block\n" + - "blocktype 18 * leaves # leaves block\n" + - "blocktype 18 1 opaque # pine leaves (not biome colorized)\n" + - "blocktype 18 2 opaque # birch leaves (not biome colorized)\n" + - "blocktype 31 * grass # tall grass block\n" + - "blocktype 106 * foliage # vines block\n" + - "blocktype 169 * grass # biomes o plenty holy grass\n" + - "blocktype 1920 * grass # biomes o plenty plant\n" + - "blocktype 1923 * opaque # biomes o plenty leaves 1\n" + - "blocktype 1924 * opaque # biomes o plenty leaves 2\n" + - "blocktype 1925 * foliage # biomes o plenty foliage\n" + - "blocktype 1926 * opaque # biomes o plenty fruit leaf block\n" + - "blocktype 1932 * foliage # biomes o plenty tree moss\n" + - "blocktype 1962 * leaves # biomes o plenty colorized leaves\n" + - "blocktype 2164 * leaves # twilight forest leaves\n" + - "blocktype 2177 * leaves # twilight forest magic leaves\n" + - "blocktype 2204 * leaves # extrabiomesXL green leaves\n" + - "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + - "blocktype 3257 * opaque # natura berry bush\n" + - "blocktype 3272 * opaque # natura darkwood leaves\n" + - "blocktype 3259 * leaves # natura flora leaves\n" + - "blocktype 3278 * opaque # natura rare leaves\n" + - "blocktype 3258 * opaque # natura sakura leaves\n" - ); - + + fout.write("block minecraft:yellow_flower * 60ffff00 # make dandelions more yellow\n" + + "block minecraft:red_flower 0 60ff0000 # make poppy more red\n" + + "block minecraft:red_flower 1 601c92d6 # make Blue Orchid more red\n" + + "block minecraft:red_flower 2 60b865fb # make Allium more red\n" + + "block minecraft:red_flower 3 60e4eaf2 # make Azure Bluet more red\n" + + "block minecraft:red_flower 4 60d33a17 # make Red Tulip more red\n" + + "block minecraft:red_flower 5 60e17124 # make Orange Tulip more red\n" + + "block minecraft:red_flower 6 60ffffff # make White Tulip more red\n" + + "block minecraft:red_flower 7 60eabeea # make Pink Tulip more red\n" + + "block minecraft:red_flower 8 60eae6ad # make Oxeye Daisy more red\n" + + "block minecraft:double_plant 0 60ffff00 # make Sunflower more Yellow-orrange\n" + + "block minecraft:double_plant 1 d09f78a4 # make Lilac more pink\n" + + "block minecraft:double_plant 4 60ff0000 # make Rose Bush more red\n" + + "block minecraft:double_plant 5 d0e3b8f7 # make Peony more red\n" + + "blocktype minecraft:grass * grass # grass block\n" + + "blocktype minecraft:flowing_water * water # flowing water block\n" + + "blocktype minecraft:water * water # still water block\n" + + "blocktype minecraft:leaves * leaves # leaves block\n" + + "blocktype minecraft:leaves 1 opaque # pine leaves (not biome colorized)\n" + + "blocktype minecraft:leaves 2 opaque # birch leaves (not biome colorized)\n" + + "blocktype minecraft:tallgrass * grass # tall grass block\n" + + "blocktype minecraft:vine * foliage # vines block\n"); + //TODO: Find out the names and readd these overwrites + // + "blocktype 169 * grass # biomes o plenty holy grass\n" + // + "blocktype 1920 * grass # biomes o plenty plant\n" + // + "blocktype 1923 * opaque # biomes o plenty leaves 1\n" + // + "blocktype 1924 * opaque # biomes o plenty leaves 2\n" + // + "blocktype 1925 * foliage # biomes o plenty foliage\n" + // + "blocktype 1926 * opaque # biomes o plenty fruit leaf block\n" + // + "blocktype 1932 * foliage # biomes o plenty tree moss\n" + // + "blocktype 1962 * leaves # biomes o plenty colorized leaves\n" + // + "blocktype 2164 * leaves # twilight forest leaves\n" + // + "blocktype 2177 * leaves # twilight forest magic leaves\n" + // + "blocktype 2204 * leaves # extrabiomesXL green leaves\n" + // + "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + // + "blocktype 3257 * opaque # natura berry bush\n" + // + "blocktype 3272 * opaque # natura darkwood leaves\n" + // + "blocktype 3259 * leaves # natura flora leaves\n" + // + "blocktype 3278 * opaque # natura rare leaves\n" + // + "blocktype 3258 * opaque # natura sakura leaves\n" } catch (IOException e) { - RegionManager.logError("saving block overrides: could not write to '%s'", f); - + RegionManager.logError( + "saving block overrides: could not write to '%s'", f); + } finally { if (fout != null) { try { fout.close(); - } catch (IOException e) {} + } catch (IOException e) { + } } } } + + public class BlockData { + public int color = 0; + public BlockType type = BlockType.NORMAL; + } } diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 0e696d5d..546ba2b2 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -1,18 +1,19 @@ package mapwriter.region; +import mapwriter.config.Config; + public class ChunkRender { - + public static final byte FLAG_UNPROCESSED = 0; public static final byte FLAG_NON_OPAQUE = 1; public static final byte FLAG_OPAQUE = 2; - // values that change how height shading algorithm works public static final double brightenExponent = 0.35; public static final double darkenExponent = 0.35; public static final double brightenAmplitude = 0.7; public static final double darkenAmplitude = 1.4; - + // get the height shading of a pixel. // requires the pixel to the west and the pixel to the north to have their // heights stored in the alpha channel to work. @@ -23,7 +24,7 @@ public class ChunkRender { public static double getHeightShading(int height, int heightW, int heightN) { int samples = 0; int heightDiff = 0; - + if ((heightW > 0) && (heightW < 255)) { heightDiff += height - heightW; samples++; @@ -33,37 +34,44 @@ public static double getHeightShading(int height, int heightW, int heightN) { heightDiff += height - heightN; samples++; } - + double heightDiffFactor = 0.0; if (samples > 0) { heightDiffFactor = (double) heightDiff / ((double) samples); } - - // emphasize small differences in height, but as the difference in height increases, + + // emphasize small differences in height, but as the difference in + // height increases, // don't increase so much - // TODO: probably more accurate to use atan here rather than a fractional - // exponent. - return Math.atan(heightDiffFactor) *0.5; - //return Math.atan(heightDiffFactor) *0.4; - //return Math.atan(heightDiffFactor); - //return (heightDiffFactor >= 0.0) ? Math.pow(heightDiffFactor, brightenExponent) * brightenAmplitude : -Math.pow(-heightDiffFactor, darkenExponent) * darkenAmplitude; + if (Config.moreRealisticMap) { + return Math.atan(heightDiffFactor) * 0.3; + } + + return (heightDiffFactor >= 0.0) ? Math.pow(heightDiffFactor + * (1 / 255.0), brightenExponent) + * brightenAmplitude : -Math.pow( + -(heightDiffFactor * (1 / 255.0)), darkenExponent) + * darkenAmplitude; } - - // calculate the colour of a pixel by alpha blending the colour of each block + + // calculate the colour of a pixel by alpha blending the colour of each + // block // in a column until an opaque block is reached. // y is topmost block height to start rendering at. - // for maps without a ceiling y is simply the height of the highest block in that chunk. - // for maps with a ceiling y is the height of the first non opaque block starting from + // for maps without a ceiling y is simply the height of the highest block in + // that chunk. + // for maps with a ceiling y is the height of the first non opaque block + // starting from // the ceiling. // // for every block in the column starting from the highest: - // - get the block colour - // - get the biome shading - // - extract colour components as doubles in the range [0.0, 1.0] - // - the shaded block colour is simply the block colour multiplied - // by the biome shading for each component - // - this shaded block colour is alpha blended with the running - // colour for this column + // - get the block colour + // - get the biome shading + // - extract colour components as doubles in the range [0.0, 1.0] + // - the shaded block colour is simply the block colour multiplied + // by the biome shading for each component + // - this shaded block colour is alpha blended with the running + // colour for this column // // so the final map colour is an alpha blended stack of all the // individual shaded block colours in the sequence [yStart .. yEnd] @@ -71,7 +79,8 @@ public static double getHeightShading(int height, int heightW, int heightN) { // note that the "front to back" alpha blending algorithm is used // rather than the more common "back to front". // - public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, int z, int heightW, int heightN) { + public static int getColumnColour(BlockColours bc, IChunk chunk, int x, + int y, int z, int heightW, int heightN) { double a = 1.0; double r = 0.0; double g = 0.0; @@ -80,76 +89,78 @@ public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, i int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); int c1 = bc.getColour(blockAndMeta); int alpha = (c1 >> 24) & 0xff; - - //this is the color that gets returned for air, so set aplha to 0 so the game continues to the next block in the colum - if (c1 == -8650628) - { + + // this is the color that gets returned for air, so set aplha to 0 + // so the game continues to the next block in the colum + if (c1 == -8650628) { alpha = 0; } - + // no need to process block if it is transparent if (alpha > 0) { int biome = chunk.getBiome(x, z); int c2 = bc.getBiomeColour(blockAndMeta, biome); - + // extract colour components as normalized doubles double c1A = (double) (alpha) / 255.0; double c1R = (double) ((c1 >> 16) & 0xff) / 255.0; - double c1G = (double) ((c1 >> 8) & 0xff) / 255.0; - double c1B = (double) ((c1 >> 0) & 0xff) / 255.0; - + double c1G = (double) ((c1 >> 8) & 0xff) / 255.0; + double c1B = (double) ((c1 >> 0) & 0xff) / 255.0; + // c2A is implicitly 1.0 (opaque) double c2R = (double) ((c2 >> 16) & 0xff) / 255.0; - double c2G = (double) ((c2 >> 8) & 0xff) / 255.0; - double c2B = (double) ((c2 >> 0) & 0xff) / 255.0; - + double c2G = (double) ((c2 >> 8) & 0xff) / 255.0; + double c2B = (double) ((c2 >> 0) & 0xff) / 255.0; + // alpha blend and multiply r = r + (a * c1A * c1R * c2R); g = g + (a * c1A * c1G * c2G); b = b + (a * c1A * c1B * c2B); a = a * (1.0 - c1A); } - //break when an opaque block is encountered + // break when an opaque block is encountered if (alpha == 255) { break; } } - + /* - // darken blocks depending on how far away they are from this depth slice - if (depth != 0) { - int bottomOfSlice = maxHeight - ((depth + 1) * maxHeight / Mw.HEIGHT_LEVELS) - 1; - if (yRange[0] < bottomOfSlice) { - shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / (double) maxHeight); - } - }*/ - + * // darken blocks depending on how far away they are from this depth + * slice if (depth != 0) { int bottomOfSlice = maxHeight - ((depth + 1) + * * maxHeight / Mw.HEIGHT_LEVELS) - 1; if (yRange[0] < bottomOfSlice) { + * shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / + * (double) maxHeight); } } + */ + double heightShading = getHeightShading(y, heightW, heightN); int lightValue = chunk.getLightValue(x, y + 1, z); double lightShading = (double) lightValue / 15.0; double shading = (heightShading + 1.0) * lightShading; - + // apply the shading r = Math.min(Math.max(0.0, r * shading), 1.0); g = Math.min(Math.max(0.0, g * shading), 1.0); b = Math.min(Math.max(0.0, b * shading), 1.0); - - // now we have our final RGB values as doubles, convert to a packed ARGB pixel. - return ((y & 0xff) << 24) | - ((((int) (r * 255.0)) & 0xff) << 16) | - ((((int) (g * 255.0)) & 0xff) << 8) | - ((((int) (b * 255.0)) & 0xff)); + + // now we have our final RGB values as doubles, convert to a packed ARGB + // pixel. + return ((y & 0xff) << 24) | ((((int) (r * 255.0)) & 0xff) << 16) + | ((((int) (g * 255.0)) & 0xff) << 8) + | ((((int) (b * 255.0)) & 0xff)); } - + static int getPixelHeightN(int[] pixels, int offset, int scanSize) { - return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) : -1; + return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) + : -1; } - + static int getPixelHeightW(int[] pixels, int offset, int scanSize) { - return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) : -1; + return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) + : -1; } - - public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) { + + public static void renderSurface(BlockColours bc, IChunk chunk, + int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) { int chunkMaxY = chunk.getMaxY(); for (int z = 0; z < MwChunk.SIZE; z++) { for (int x = 0; x < MwChunk.SIZE; x++) { @@ -163,53 +174,51 @@ public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, in for (y = 127; y >= 0; y--) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - - if (bc.getColour(blockAndMeta) == -8650628) - { + + if (bc.getColour(blockAndMeta) == -8650628) { alpha = 0; } - + if (alpha != 0xff) { break; } } } else { - y = chunkMaxY-1; + y = chunkMaxY - 1; } - + int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour( - bc, chunk, x, y, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize) - ); + pixels[pixelOffset] = getColumnColour(bc, chunk, x, y, z, + getPixelHeightW(pixels, pixelOffset, scanSize), + getPixelHeightN(pixels, pixelOffset, scanSize)); } } } - - public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, int startY, byte[] mask) { + + public static void renderUnderground(BlockColours bc, IChunk chunk, + int[] pixels, int offset, int scanSize, int startY, byte[] mask) { startY = Math.min(Math.max(0, startY), 255); for (int z = 0; z < MwChunk.SIZE; z++) { for (int x = 0; x < MwChunk.SIZE; x++) { - + // only process columns where the mask bit is set. // process all columns if mask is null. if ((mask != null) && ((mask[(z * 16) + x]) != FLAG_NON_OPAQUE)) { continue; } - - // get the last non transparent block before the first opaque block searching + + // get the last non transparent block before the first opaque + // block searching // towards the sky from startY int lastNonTransparentY = startY; for (int y = startY; y < chunk.getMaxY(); y++) { int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - - if (bc.getColour(blockAndMeta) == -8650628) - { + + if (bc.getColour(blockAndMeta) == -8650628) { alpha = 0; } - + if (alpha == 0xff) { break; } @@ -217,13 +226,12 @@ public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels lastNonTransparentY = y; } } - + int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour( - bc, chunk, x, lastNonTransparentY, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize) - ); + pixels[pixelOffset] = getColumnColour(bc, chunk, x, + lastNonTransparentY, z, + getPixelHeightW(pixels, pixelOffset, scanSize), + getPixelHeightN(pixels, pixelOffset, scanSize)); } } } diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index fa9a2dff..4c936ae2 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -20,20 +20,22 @@ public class MwChunk implements IChunk { public static final int SIZE = 16; - + public final int x; public final int z; public final int dimension; - - char[][] dataArray = new char[16][]; + + char[][] dataArray = new char[16][]; public final byte[][] lightingArray; public final Map tileentityMap; - + public final byte[] biomeArray; - + public final int maxY; - - public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) { + + public MwChunk(int x, int z, int dimension, char[][] data, + byte[][] lightingArray, byte[] biomeArray, + Map TileEntityMap) { this.x = x; this.z = z; this.dimension = dimension; @@ -49,340 +51,367 @@ public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArra } this.maxY = maxY; } - + public String toString() { return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); } - + // load from anvil file - public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { - + public static MwChunk read(int x, int z, int dimension, + RegionFileCache regionFileCache) { + byte[] biomeArray = null; byte[][] lsbArray = new byte[16][]; char[][] data = new char[16][]; byte[][] lightingArray = new byte[16][]; Map TileEntityMap = new HashMap(); - - DataInputStream dis = null; - RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); - if (!regionFile.isOpen()) { - if (regionFile.exists()) { - regionFile.open(); - } - } - - if (regionFile.isOpen()) { - dis = regionFile.getChunkDataInputStream(x & 31, z & 31); - } - + + DataInputStream dis = null; + RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, + dimension); + if (!regionFile.isOpen()) { + if (regionFile.exists()) { + regionFile.open(); + } + } + + if (regionFile.isOpen()) { + dis = regionFile.getChunkDataInputStream(x & 31, z & 31); + } + if (dis != null) { try { - - //chunk NBT structure: + + // chunk NBT structure: // - //COMPOUND "" - //COMPOUND "level" - // INT "xPos" - // INT "zPos" - // LONG "LastUpdate" - // BYTE "TerrainPopulated" - // BYTE_ARRAY "Biomes" - // INT_ARRAY "HeightMap" - // LIST(COMPOUND) "Sections" - // BYTE "Y" - // BYTE_ARRAY "Blocks" - // BYTE_ARRAY "Add" - // BYTE_ARRAY "Data" - // BYTE_ARRAY "BlockLight" - // BYTE_ARRAY "SkyLight" - // END - // LIST(COMPOUND) "Entities" - // LIST(COMPOUND) "TileEntities" - // LIST(COMPOUND) "TileTicks" - //END - //END + // COMPOUND "" + // COMPOUND "level" + // INT "xPos" + // INT "zPos" + // LONG "LastUpdate" + // BYTE "TerrainPopulated" + // BYTE_ARRAY "Biomes" + // INT_ARRAY "HeightMap" + // LIST(COMPOUND) "Sections" + // BYTE "Y" + // BYTE_ARRAY "Blocks" + // BYTE_ARRAY "Add" + // BYTE_ARRAY "Data" + // BYTE_ARRAY "BlockLight" + // BYTE_ARRAY "SkyLight" + // END + // LIST(COMPOUND) "Entities" + // LIST(COMPOUND) "TileEntities" + // LIST(COMPOUND) "TileTicks" + // END + // END NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); - + int xNbt = level.getInteger("xPos"); int zNbt = level.getInteger("zPos"); - + if ((xNbt != x) || (zNbt != z)) { - RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); + RegionManager.logWarning( + "chunk (%d, %d) has NBT coords (%d, %d)", x, z, + xNbt, zNbt); } - + NBTTagList sections = level.getTagList("Sections", 10); - - for (int k = 0; k < sections.tagCount(); ++k) - { - NBTTagCompound section = sections.getCompoundTagAt(k); - int y = section.getByte("Y"); - lsbArray[y & 0xf] = section.getByteArray("Blocks"); - NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); - NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; - - data[y & 0xf] = new char[lsbArray[y].length]; - - for (int l = 0; l < data[y & 0xf].length; ++l) - { - int i1 = l & 15; - int j1 = l >> 8 & 15; - int k1 = l >> 4 & 15; - int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; - data[y & 0xf][l] = (char)(l1 << 12 | (lsbArray[y][l] & 255) << 4 | nibblearray.get(i1, j1, k1)); - } - } + + for (int k = 0; k < sections.tagCount(); ++k) { + NBTTagCompound section = sections.getCompoundTagAt(k); + int y = section.getByte("Y"); + lsbArray[y & 0xf] = section.getByteArray("Blocks"); + NibbleArray nibblearray = new NibbleArray( + section.getByteArray("Data")); + NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray( + section.getByteArray("Add")) : null; + + data[y & 0xf] = new char[lsbArray[y].length]; + + for (int l = 0; l < data[y & 0xf].length; ++l) { + int i1 = l & 15; + int j1 = l >> 8 & 15; + int k1 = l >> 4 & 15; + int l1 = nibblearray1 != null ? nibblearray1.get(i1, + j1, k1) : 0; + data[y & 0xf][l] = (char) (l1 << 12 + | (lsbArray[y][l] & 255) << 4 | nibblearray + .get(i1, j1, k1)); + } + } biomeArray = level.getByteArray("Biomes"); - NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); - - if (nbttaglist2 != null) - { - for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) - { - NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); - TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); - if (tileentity != null) - { - TileEntityMap.put(tileentity.getPos(), tileentity); - } - } - } - - + NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); + + if (nbttaglist2 != null) { + for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) { + NBTTagCompound nbttagcompound4 = nbttaglist2 + .getCompoundTagAt(i1); + TileEntity tileentity = TileEntity + .createAndLoadEntity(nbttagcompound4); + if (tileentity != null) { + TileEntityMap.put(tileentity.getPos(), tileentity); + } + } + } + } catch (IOException e) { - RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); + RegionManager.logError( + "%s: could not read chunk (%d, %d) from region file\n", + e, x, z); } finally { - try { dis.close(); } - catch (IOException e) { - RegionManager.logError("MwChunk.read: %s while closing input stream", e); + try { + dis.close(); + } catch (IOException e) { + RegionManager.logError( + "MwChunk.read: %s while closing input stream", e); } } - //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); + // this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, + // empty); } else { - //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); + // this.log("MwChunk.read: chunk (%d, %d) input stream is null", + // this.x, this.z); } - - return new MwChunk(x, z, dimension,data , lightingArray, biomeArray,TileEntityMap); + + return new MwChunk(x, z, dimension, data, lightingArray, biomeArray, + TileEntityMap); } - + public boolean isEmpty() { return (this.maxY <= 0); } - + public int getBiome(int x, int z) { - return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; + return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) + | (x & 0xf)]) & 0xff + : 0; } - + public int getLightValue(int x, int y, int z) { - //int yi = (y >> 4) & 0xf; - //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; - - //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); + // int yi = (y >> 4) & 0xf; + // int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + // int light = ((this.lightingArray != null) && (this.lightingArray[yi] + // != null)) ? this.lightingArray[yi][offset >> 1] : 15; + + // return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); return 15; } - + public int getMaxY() { return this.maxY; } - + public int getBlockAndMetadata(int x, int y, int z) { int yi = (y >> 4) & 0xf; int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - + int lsb = 0; int msb = 0; int meta = 0; - - BlockPos pos = new BlockPos(x,y,z); - - char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; - - //check if the block has a tileentity if so use the blockdata in the tileentity - //(forgemultipart and carpenterblocks both save the block to be rendered in the tileentity map) - if (this.tileentityMap.containsKey(pos)) - { - - TileEntity value = (TileEntity)this.tileentityMap.get(pos); - NBTTagCompound tag = new NBTTagCompound(); - value.writeToNBT(tag); - int id = 0; - - if (tag.getString("id") == "savedMultipart") - { - String material = tag.getTagList("parts", 10).getCompoundTagAt(0).getString("material"); + + BlockPos pos = new BlockPos(x, y, z); + + char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] + : 0; + + // check if the block has a tileentity if so use the blockdata in the + // tileentity + // (forgemultipart and carpenterblocks both save the block to be + // rendered in the tileentity map) + if (this.tileentityMap.containsKey(pos)) { + + TileEntity value = (TileEntity) this.tileentityMap.get(pos); + NBTTagCompound tag = new NBTTagCompound(); + value.writeToNBT(tag); + int id = 0; + + if (tag.getString("id") == "savedMultipart") { + String material = tag.getTagList("parts", 10) + .getCompoundTagAt(0).getString("material"); int end = material.indexOf("_"); - - //block with metadata - if (end != -1) - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5, end))); - - lsb = (id & 255); - - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - meta = Integer.parseInt(material.substring(end+1)); + + // block with metadata + if (end != -1) { + id = Block.getIdFromBlock(Block.getBlockFromName(material + .substring(5, end))); + + lsb = (id & 255); + + if (id > 255) { + msb = (id & 3840) >> 8; + } else { + msb = 0; + } + + meta = Integer.parseInt(material.substring(end + 1)); } - //block without metadata - else - { - id = Block.getIdFromBlock(Block.getBlockFromName(material.substring(5))); - + // block without metadata + else { + id = Block.getIdFromBlock(Block.getBlockFromName(material + .substring(5))); + lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} + if (id > 255) { + msb = (id & 3840) >> 8; + } else { + msb = 0; + } } - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - else if (tag.getString("id") =="TileEntityCarpentersBlock") - { + data = (char) (((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } else if (tag.getString("id") == "TileEntityCarpentersBlock") { NBTTagList TagList = tag.getTagList("cbAttrList", 10); String sid = TagList.getCompoundTagAt(0).getString("id"); - String smeta = TagList.getCompoundTagAt(0).getString("Damage"); - if (sid != "") - { - id = Integer.parseInt(sid.substring(0, sid.length()-1)); - + String smeta = TagList.getCompoundTagAt(0).getString("Damage"); + if (sid != "") { + id = Integer.parseInt(sid.substring(0, sid.length() - 1)); + lsb = (id & 255); - if (id > 255){msb = (id & 3840) >> 8;} - else {msb = 0;} - - if (smeta != "") - { - meta = Integer.parseInt(smeta.substring(0, smeta.length()-1)); + if (id > 255) { + msb = (id & 3840) >> 8; + } else { + msb = 0; + } + + if (smeta != "") { + meta = Integer.parseInt(smeta.substring(0, + smeta.length() - 1)); } - - data = (char)(((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + + data = (char) (((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); } - } - } + } + } - //return ((offset & 1) == 1) ? - // ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : - return (int)data; + return (int) data; } - - //changed to use the NBTTagCompound that minecraft uses. this makes the local way of saving anvill data the same as Minecraft world data - private NBTTagCompound writeChunkToNBT() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound.setTag("Level", nbttagcompound1); - - nbttagcompound1.setInteger("xPos", this.x); - nbttagcompound1.setInteger("zPos", this.z); - - NBTTagList nbttaglist = new NBTTagList(); - - NBTTagCompound nbttagcompound2; - - for (int y = 0; y < this.dataArray.length; y++) - { - if (this.dataArray[y] != null) - { - byte[] abyte = new byte[this.dataArray[y].length]; - NibbleArray nibblearray = new NibbleArray(); - NibbleArray nibblearray1 = null; - - for (int k = 0; k < this.dataArray[y].length; ++k) - { - char c0 = this.dataArray[y][k]; - int l = k & 15; - int i1 = k >> 8 & 15; - int j1 = k >> 4 & 15; - - if (c0 >> 12 != 0) - { - if (nibblearray1 == null) - { - nibblearray1 = new NibbleArray(); - } - - nibblearray1.set(l, i1, j1, c0 >> 12); - } - - abyte[k] = (byte)(c0 >> 4 & 255); - nibblearray.set(l, i1, j1, c0 & 15); - } - - - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Y", (byte)y); - nbttagcompound2.setByteArray("Blocks", abyte); - - if (nibblearray1 != null) - { - nbttagcompound2.setByteArray("Add", nibblearray1.getData()); - } - - nbttagcompound2.setByteArray("Data", nibblearray.getData()); - nbttaglist.appendTag(nbttagcompound2); - } - - nbttagcompound1.setTag("Sections", nbttaglist); - } - nbttagcompound1.setByteArray("Biomes", this.biomeArray); - - NBTTagList nbttaglist3 = new NBTTagList(); - - Iterator iterator1 = this.tileentityMap.values().iterator(); - - while (iterator1.hasNext()) - { - TileEntity tileentity = (TileEntity)iterator1.next(); - nbttagcompound2 = new NBTTagCompound(); - try { - tileentity.writeToNBT(nbttagcompound2); - nbttaglist3.appendTag(nbttagcompound2); - } - catch (Exception e) - { - FMLLog.log(Level.ERROR, e, - "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", - tileentity.getClass().getName()); - } - } - nbttagcompound1.setTag("TileEntities", nbttaglist3); - - return nbttagcompound; - } - + + // changed to use the NBTTagCompound that minecraft uses. this makes the + // local way of saving anvill data the same as Minecraft world data + private NBTTagCompound writeChunkToNBT() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound.setTag("Level", nbttagcompound1); + + nbttagcompound1.setInteger("xPos", this.x); + nbttagcompound1.setInteger("zPos", this.z); + + NBTTagList nbttaglist = new NBTTagList(); + + NBTTagCompound nbttagcompound2; + + for (int y = 0; y < this.dataArray.length; y++) { + if (this.dataArray[y] != null) { + byte[] abyte = new byte[this.dataArray[y].length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < this.dataArray[y].length; ++k) { + char c0 = this.dataArray[y][k]; + int l = k & 15; + int i1 = k >> 8 & 15; + int j1 = k >> 4 & 15; + + if (c0 >> 12 != 0) { + if (nibblearray1 == null) { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte) (c0 >> 4 & 255); + nibblearray.set(l, i1, j1, c0 & 15); + } + + nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Y", (byte) y); + nbttagcompound2.setByteArray("Blocks", abyte); + + if (nibblearray1 != null) { + nbttagcompound2.setByteArray("Add", nibblearray1.getData()); + } + + nbttagcompound2.setByteArray("Data", nibblearray.getData()); + nbttaglist.appendTag(nbttagcompound2); + } + + nbttagcompound1.setTag("Sections", nbttaglist); + } + nbttagcompound1.setByteArray("Biomes", this.biomeArray); + + NBTTagList nbttaglist3 = new NBTTagList(); + + Iterator iterator1 = this.tileentityMap.values().iterator(); + + while (iterator1.hasNext()) { + TileEntity tileentity = (TileEntity) iterator1.next(); + nbttagcompound2 = new NBTTagCompound(); + try { + tileentity.writeToNBT(nbttagcompound2); + nbttaglist3.appendTag(nbttagcompound2); + } catch (Exception e) { + FMLLog.log( + Level.ERROR, + e, + "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", + tileentity.getClass().getName()); + } + } + nbttagcompound1.setTag("TileEntities", nbttaglist3); + + return nbttagcompound; + } + public synchronized boolean write(RegionFileCache regionFileCache) { boolean error = false; - RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); + RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, + this.z << 4, this.dimension); if (!regionFile.isOpen()) { - error = regionFile.open(); - } + error = regionFile.open(); + } if (!error) { - DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); + DataOutputStream dos = regionFile.getChunkDataOutputStream( + this.x & 31, this.z & 31); if (dos != null) { - //Nbt chunkNbt = this.getNbt(); + // Nbt chunkNbt = this.getNbt(); try { - //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); - //chunkNbt.writeElement(dos); - //use minecraft build in save tool for saving the Anvil Data + // RegionManager.logInfo("writing chunk (%d, %d) to region file", + // this.x, this.z); + // chunkNbt.writeElement(dos); + // use minecraft build in save tool for saving the Anvil + // Data CompressedStreamTools.write(writeChunkToNBT(), dos); } catch (IOException e) { - RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); + RegionManager + .logError( + "%s: could not write chunk (%d, %d) to region file", + e, this.x, this.z); error = true; } finally { - try { dos.close(); } - catch (IOException e) { - RegionManager.logError("%s while closing chunk data output stream", e); + try { + dos.close(); + } catch (IOException e) { + RegionManager.logError( + "%s while closing chunk data output stream", e); } } } else { - RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); + RegionManager + .logError( + "error: could not get output stream for chunk (%d, %d)", + this.x, this.z); } } else { - RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); + RegionManager.logError( + "error: could not open region file for chunk (%d, %d)", + this.x, this.z); } - + return error; } } diff --git a/src/main/java/mapwriter/util/Texture.java b/src/main/java/mapwriter/util/Texture.java index 19ffc176..2d2be438 100644 --- a/src/main/java/mapwriter/util/Texture.java +++ b/src/main/java/mapwriter/util/Texture.java @@ -3,6 +3,7 @@ import java.nio.IntBuffer; import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -73,11 +74,23 @@ public synchronized void fillRect(int x, int y, int w, int h, int colour) { } // Copy a rectangular sub-region of dimensions 'w' x 'h' from the pixel buffer to the array 'pixels'. - public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { + public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize, TextureAtlasSprite icon) { int bufOffset = (y * this.w) + x; for (int i = 0; i < h; i++) { this.pixelBuf.position(bufOffset + (i * this.w)); this.pixelBuf.get(pixels, offset + (i * scanSize), w); + try + { + this.pixelBuf.position(bufOffset + (i * this.w)); + this.pixelBuf.get(pixels, offset + (i * scanSize), w); + } + catch (IllegalArgumentException e) + { + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (icon name: %s; height: %d; width: %d; MaxU: %f; MinU: %f; MaxV: %f; MinV: %f)", icon.getIconName(), icon.getIconHeight(), icon.getIconWidth(), icon.getMaxU(),icon.getMinU(), icon.getMaxV(),icon.getMinV()); + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (pos: %d)", bufOffset + (i * this.w)); + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (buffersize: %d)", this.pixelBuf.limit()); + } + } } diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index b3a793dd..04d77008 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -45,6 +45,8 @@ mw.config.zoomInLevels=Zoom in levels mw.config.zoomInLevels.tooltip=Max number of steps you can zoom in. Does not affect performance. mw.config.textureSize= mw.config.textureSize.tooltip= +mw.config.moreRealisticMap=Enables realistic map +mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic #Config Temp mw.config.overlayModeIndex= From e26e5aeffd0cf5a2762feda3267831bd241af3e0 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 12 Jul 2015 23:00:20 +0200 Subject: [PATCH 052/109] only reload blockcolours when the texture pack changes. --- src/main/java/mapwriter/Mw.java | 2 +- src/main/java/mapwriter/forge/EventHandler.java | 5 +++++ src/main/java/mapwriter/gui/MwGui.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index ee00b542..000833ff 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -312,7 +312,7 @@ public void load() { // mapTexture depends on config being loaded this.mapTexture = new MapTexture(this.textureSize, Config.linearTextureScaling); this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, Config.linearTextureScaling); - this.reloadBlockColours(); + //this.reloadBlockColours(); // region manager depends on config, mapTexture, and block colours this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); // overlay manager depends on mapTexture diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 4ac17127..1e7527d2 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -7,6 +7,7 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; @@ -78,4 +79,8 @@ public void renderMap(RenderGameOverlayEvent.Post event){ Mw.getInstance().onTick(); } } + @SubscribeEvent + public void onTextureStitchEventPost(TextureStitchEvent.Post event){ + mw.reloadBlockColours(); + } } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 0989edff..e83aa1b7 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -188,7 +188,7 @@ public void regenerateView() { (int) this.mapView.getHeight(), (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); - this.mw.reloadBlockColours(); + //this.mw.reloadBlockColours(); this.mw.executor.addTask2(new RebuildRegionsTask( this.mw, (int) this.mapView.getMinX(), From 13b509dac0b4671a6aabc3774bc4578cad912ce2 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 12 Jul 2015 23:48:13 +0200 Subject: [PATCH 053/109] cleanup. --- src/main/java/mapwriter/region/BlockColours.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 3905105b..2872418e 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -27,12 +27,10 @@ public class BlockColours { public static final String biomeSectionString = "[biomes]"; public static final String blockSectionString = "[blocks]"; - // private int[] bcArray = new int[MAX_BLOCKS * MAX_META]; private int[] waterMultiplierArray = new int[MAX_BIOMES]; private int[] grassMultiplierArray = new int[MAX_BIOMES]; private int[] foliageMultiplierArray = new int[MAX_BIOMES]; private LinkedHashMap bcMap = new LinkedHashMap(); - private LinkedHashMap bcOverrideMap = new LinkedHashMap(); public enum BlockType { NORMAL, GRASS, LEAVES, FOLIAGE, WATER, OPAQUE From 0ad24510057d7030d476283a292ec7987e478147 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 12 Jul 2015 23:49:10 +0200 Subject: [PATCH 054/109] minimap now remembers zoom again. fullscreen map also remembers zoom now --- src/main/java/mapwriter/config/Config.java | 6 ++++-- src/main/java/mapwriter/gui/MwGui.java | 7 ++++--- src/main/java/mapwriter/map/MapView.java | 19 ++++++++++++++++--- src/main/java/mapwriter/map/MiniMap.java | 2 +- 4 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 1984c08b..4f9a4fe0 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -51,10 +51,12 @@ public class Config { //World configuration Options - public static int overlayModeIndex = 0; public static int overlayModeIndexDef = 0; - public static int overlayZoomLevel = 0; + public static int overlayModeIndex = overlayModeIndexDef; public static int overlayZoomLevelDef = 0; + public static int overlayZoomLevel = overlayZoomLevelDef; + public static int fullScreenZoomLevelDef = 0; + public static int fullScreenZoomLevel = fullScreenZoomLevelDef; public static largeMapModeConfig largeMap = new largeMapModeConfig(Reference.catLargeMapConfig); public static smallMapModeConfig smallMap = new smallMapModeConfig(Reference.catSmallMapConfig); diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index e83aa1b7..2a1403d8 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -87,12 +87,12 @@ public boolean posWithin(int x, int y) { public MwGui(Mw mw) { this.mw = mw; this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw); + this.mapView = new MapView(this.mw, true); this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); this.mapView.setDimension(this.mw.miniMap.view.getDimension()); this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - this.mapView.setZoomLevel(0); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); this.helpLabel = new Label(); this.optionsLabel = new Label(); @@ -107,7 +107,7 @@ public MwGui(Mw mw, int dim, int x, int z){ this(mw); this.mapView.setDimension(dim); this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(0); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); } // called when gui is displayed and every time the screen @@ -475,6 +475,7 @@ public void mouseDWheelScrolled(int x, int y, int direction) { } else { int zF = (direction > 0) ? -1 : 1; this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); + Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); } } diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java index 0428d890..9418c4f1 100644 --- a/src/main/java/mapwriter/map/MapView.java +++ b/src/main/java/mapwriter/map/MapView.java @@ -35,12 +35,18 @@ public class MapView { private int maxZoom; private boolean undergroundMode; + private boolean fullscreenMap; - public MapView(Mw mw) { + public MapView(Mw mw, boolean FullscreenMap) { this.minZoom = Config.zoomInLevels; this.maxZoom = Config.zoomOutLevels; this.undergroundMode = Config.undergroundMode; - this.setZoomLevel(0); + this.fullscreenMap = FullscreenMap; + if (this.fullscreenMap) + { + this.setZoomLevel(Config.fullScreenZoomLevel); + } + this.setZoomLevel(Config.overlayZoomLevel); this.setViewCentre(mw.playerX, mw.playerZ); } @@ -88,7 +94,14 @@ public int setZoomLevel(int zoomLevel) { if (prevZoomLevel != this.zoomLevel) { this.updateZoom(); } - return this.zoomLevel; + + if (this.fullscreenMap) + { + Config.fullScreenZoomLevel = this.zoomLevel; + } + Config.overlayZoomLevel = this.zoomLevel; + + return this.zoomLevel; } private void updateZoom() { diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index e4f7894e..3ae3a0e2 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -24,7 +24,7 @@ public class MiniMap { public MiniMap(Mw mw) { // map view shared between large and small map modes - this.view = new MapView(mw); + this.view = new MapView(mw, false); this.view.setZoomLevel(Config.overlayZoomLevel); // small map mode From 4f3a7e6b4984c1c4eadac34a730a7e79f4f485f3 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 14 Jul 2015 01:03:15 +0200 Subject: [PATCH 055/109] added myself to the credits in the modinfo, also added the update url to the curse site. --- src/main/resources/mcmod.info | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index f1042b56..7ff06307 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,16 +1,16 @@ -[ -{ - "modid": "MapWriter", - "name": "MapWriter", - "description": "An open source mini map mod", - "version": "${version}", - "mcversion": "${mcversion}", - "url": "http://www.minecraftforum.net/topic/1570989-/", - "updateUrl": "", - "authorList": ["mapwriter"], - "credits": "chrixian, ProfMobius, taelnia, jk-5", - "logoFile": "", - "screenshots": [], - "dependencies": [] -} -] +[ +{ + "modid": "MapWriter", + "name": "MapWriter", + "description": "An open source mini map mod", + "version": "${version}", + "mcversion": "${mcversion}", + "url": "http://www.minecraftforum.net/topic/1570989-/", + "updateUrl": "http://www.curse.com/mc-mods/Minecraft/231387-mapwriter-2", + "authorList": ["mapwriter"], + "credits": "chrixian, ProfMobius, taelnia, jk-5, Vectron", + "logoFile": "", + "screenshots": [], + "dependencies": [] +} +] From a76e80aa6b4c09e729d0b48454d3a384c2d9f58a Mon Sep 17 00:00:00 2001 From: Thijs Date: Thu, 16 Jul 2015 13:10:29 +0200 Subject: [PATCH 056/109] Cleanup --- src/main/java/mapwriter/BlockColourGen.java | 4 +--- src/main/java/mapwriter/region/BlockColours.java | 2 -- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index 19cc7509..2eb6a8a7 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -1,12 +1,10 @@ package mapwriter; import mapwriter.region.BlockColours; -import mapwriter.region.BlockColours.BlockType; import mapwriter.util.Logging; import mapwriter.util.Render; import mapwriter.util.Texture; import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -117,7 +115,7 @@ public static void genBlockColours(BlockColours bc) { } for (int dv = 0; dv < 16; dv++) { - int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); + //int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); int blockColour = 0; if (block != null) { diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 2872418e..8f0d0ca2 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -471,7 +471,6 @@ public void saveBlocks(Writer fout) throws IOException { for (Map.Entry entry : bcMap.entrySet()) { String[] BlockAndMeta = entry.getKey().split(" "); String block = BlockAndMeta[0]; - String meta = BlockAndMeta[1]; String color = String.format("%08x", entry.getValue().color); @@ -496,7 +495,6 @@ public void saveBlockTypes(Writer fout) throws IOException { for (Map.Entry entry : bcMap.entrySet()) { String[] BlockAndMeta = entry.getKey().split(" "); String block = BlockAndMeta[0]; - String meta = BlockAndMeta[1]; String Type = getBlockTypeAsString(entry.getValue().type); From 35bcda1d4def920f1bc2b623237783bf0f7ae800 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 16 Jul 2015 22:54:50 +0200 Subject: [PATCH 057/109] Testing update checker --- version.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 version.json diff --git a/version.json b/version.json new file mode 100644 index 00000000..e36bf5ad --- /dev/null +++ b/version.json @@ -0,0 +1,20 @@ +{ + "versionList": [ + { + "mcVersion":"Minecraft 1.7.10", + "modVersion":"2.1.5", + "changeLog": [], + "updateURL":"http://minecraft.curseforge.com/mc-mods/231387-mapwriter-2/files/", + "isDirectLink":"false", + "newFileName":"" + }, + { + "mcVersion":"Minecraft 1.8", + "modVersion":"2.2.5", + "changeLog": [], + "updateURL":"http://minecraft.curseforge.com/mc-mods/231387-mapwriter-2/files/", + "isDirectLink":"false", + "newFileName":"" + } + ] +} \ No newline at end of file From c73a28c8cc6bcad48b06d42eaddb01429be3652d Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 17 Jul 2015 19:48:41 +0200 Subject: [PATCH 058/109] version checking added, and probably some formatting. --- .../java/mapwriter/forge/ClientProxy.java | 75 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 304 ++-- src/main/java/mapwriter/gui/MwGui.java | 1361 +++++++++-------- src/main/java/mapwriter/util/Reference.java | 78 +- src/main/java/mapwriter/util/Utils.java | 472 +++--- .../java/mapwriter/util/VersionCheck.java | 78 + 6 files changed, 1268 insertions(+), 1100 deletions(-) create mode 100644 src/main/java/mapwriter/util/VersionCheck.java diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index b4ae6cc1..38e146d0 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -1,35 +1,40 @@ -package mapwriter.forge; - -import java.io.File; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.config.ConfigurationHandler; -import mapwriter.overlay.OverlayGrid; -import mapwriter.overlay.OverlaySlime; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.FMLCommonHandler; - -public class ClientProxy extends CommonProxy { - - public void preInit(File configFile) - { - ConfigurationHandler.init(configFile); - FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); - } - - public void load() { - EventHandler eventHandler = new EventHandler(Mw.getInstance()); - MinecraftForge.EVENT_BUS.register(eventHandler); - FMLCommonHandler.instance().bus().register(eventHandler); - - MwKeyHandler keyEventHandler = new MwKeyHandler(); - FMLCommonHandler.instance().bus().register(keyEventHandler); - MinecraftForge.EVENT_BUS.register(keyEventHandler); - } - - public void postInit() { - MwAPI.registerDataProvider("Slime", new OverlaySlime()); - MwAPI.registerDataProvider("Grid", new OverlayGrid()); - } -} +package mapwriter.forge; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.config.ConfigurationHandler; +import mapwriter.overlay.OverlayGrid; +import mapwriter.overlay.OverlaySlime; +import mapwriter.util.VersionCheck; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.FMLCommonHandler; + +public class ClientProxy extends CommonProxy { + + public void preInit(File configFile) + { + ConfigurationHandler.init(configFile); + FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); + } + + public void load() { + EventHandler eventHandler = new EventHandler(Mw.getInstance()); + MinecraftForge.EVENT_BUS.register(eventHandler); + FMLCommonHandler.instance().bus().register(eventHandler); + + MwKeyHandler keyEventHandler = new MwKeyHandler(); + FMLCommonHandler.instance().bus().register(keyEventHandler); + MinecraftForge.EVENT_BUS.register(keyEventHandler); + } + + public void postInit() { + VersionCheck versionCheck = new VersionCheck(); + Thread versionCheckThread = new Thread(versionCheck, "Version Check"); + versionCheckThread.start(); + + MwAPI.registerDataProvider("Slime", new OverlaySlime()); + MwAPI.registerDataProvider("Grid", new OverlayGrid()); + } +} diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index 0c300675..c4a48e21 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -1,152 +1,152 @@ -package mapwriter.gui; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.config.Config; -import mapwriter.config.ConfigurationHandler; -import mapwriter.util.Reference; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; -import net.minecraftforge.fml.client.config.GuiConfig; -import net.minecraftforge.fml.client.config.GuiConfigEntries; -import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; -import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; -import net.minecraftforge.fml.client.config.GuiUtils; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class ModGuiConfig extends GuiConfig -{ - public ModGuiConfig(GuiScreen guiScreen) - { - super(guiScreen, - getConfigElements(), - //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), - Reference.MOD_ID, - "Options", - false, - false, - GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); - } - - /** Compiles a list of config elements */ - private static List getConfigElements() - { - List list = new ArrayList(); - - //Add categories to config GUI - list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); - list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); - list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); - list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); - return list; - } - - /** Creates a button linking to another screen where all options of the category are available */ - private static IConfigElement categoryElement(String category, String name, String tooltip_key) - { - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); - } - - public static class ModBooleanEntry extends ButtonEntry - { - protected final boolean beforeValue; - protected boolean currentValue; - - public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) - { - super(owningScreen, owningEntryList, configElement); - this.beforeValue = Boolean.valueOf(configElement.get().toString()); - this.currentValue = beforeValue; - this.btnValue.enabled = enabled(); - updateValueButtonText(); - } - - @Override - public void updateValueButtonText() - { - this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); - btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); - } - - @Override - public void valueButtonPressed(int slotIndex) - { - if (enabled()) - currentValue = !currentValue; - } - - @Override - public boolean isDefault() - { - return currentValue == Boolean.valueOf(configElement.getDefault().toString()); - } - - @Override - public void setToDefault() - { - if (enabled()) - { - currentValue = Boolean.valueOf(configElement.getDefault().toString()); - updateValueButtonText(); - } - } - - @Override - public boolean isChanged() - { - return currentValue != beforeValue; - } - - @Override - public void undoChanges() - { - if (enabled()) - { - currentValue = beforeValue; - updateValueButtonText(); - } - } - - @Override - public boolean saveConfigElement() - { - if (enabled() && isChanged()) - { - configElement.set(currentValue); - return configElement.requiresMcRestart(); - } - return false; - } - - @Override - public Boolean getCurrentValue() - { - return currentValue; - } - - @Override - public Boolean[] getCurrentValues() - { - return new Boolean[] { getCurrentValue() }; - } - - @Override - public boolean enabled() - { - for (IConfigEntry entry : this.owningEntryList.listEntries) - { - if (entry.getName().equals("circular") && entry instanceof BooleanEntry) - { - return Boolean.valueOf(entry.getCurrentValue().toString()); - } - } - - return true; - } - } -} +package mapwriter.gui; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.config.Config; +import mapwriter.config.ConfigurationHandler; +import mapwriter.util.Reference; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.config.GuiConfigEntries; +import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.ButtonEntry; +import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; +import net.minecraftforge.fml.client.config.GuiUtils; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class ModGuiConfig extends GuiConfig +{ + public ModGuiConfig(GuiScreen guiScreen) + { + super(guiScreen, + getConfigElements(), + //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + Reference.MOD_ID, + "Options", + false, + false, + GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); + } + + /** Compiles a list of config elements */ + private static List getConfigElements() + { + List list = new ArrayList(); + + //Add categories to config GUI + list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); + list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); + list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); + list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); + return list; + } + + /** Creates a button linking to another screen where all options of the category are available */ + private static IConfigElement categoryElement(String category, String name, String tooltip_key) + { + return new DummyCategoryElement(name, tooltip_key, + new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); + } + + public static class ModBooleanEntry extends ButtonEntry + { + protected final boolean beforeValue; + protected boolean currentValue; + + public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) + { + super(owningScreen, owningEntryList, configElement); + this.beforeValue = Boolean.valueOf(configElement.get().toString()); + this.currentValue = beforeValue; + this.btnValue.enabled = enabled(); + updateValueButtonText(); + } + + @Override + public void updateValueButtonText() + { + this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); + btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); + } + + @Override + public void valueButtonPressed(int slotIndex) + { + if (enabled()) + currentValue = !currentValue; + } + + @Override + public boolean isDefault() + { + return currentValue == Boolean.valueOf(configElement.getDefault().toString()); + } + + @Override + public void setToDefault() + { + if (enabled()) + { + currentValue = Boolean.valueOf(configElement.getDefault().toString()); + updateValueButtonText(); + } + } + + @Override + public boolean isChanged() + { + return currentValue != beforeValue; + } + + @Override + public void undoChanges() + { + if (enabled()) + { + currentValue = beforeValue; + updateValueButtonText(); + } + } + + @Override + public boolean saveConfigElement() + { + if (enabled() && isChanged()) + { + configElement.set(currentValue); + return configElement.requiresMcRestart(); + } + return false; + } + + @Override + public Boolean getCurrentValue() + { + return currentValue; + } + + @Override + public Boolean[] getCurrentValues() + { + return new Boolean[] { getCurrentValue() }; + } + + @Override + public boolean enabled() + { + for (IConfigEntry entry : this.owningEntryList.listEntries) + { + if (entry.getName().equals("circular") && entry instanceof BooleanEntry) + { + return Boolean.valueOf(entry.getCurrentValue().toString()); + } + } + + return true; + } + } +} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 2a1403d8..338e62c5 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,648 +1,713 @@ -package mapwriter.gui; - -import java.awt.Point; -import java.io.IOException; - -import mapwriter.Mw; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.util.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - public MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - - public static MwGui instance; - - class Label { - int x = 0, y = 0, w = 1, h = 12; - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); - } - } - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw, true); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - - instance = this; - } - - public MwGui(Mw mw, int dim, int x, int z){ - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - public void exitGui() { - //MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX,0, bZ)).getY(); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); - this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), - (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension(), - this.mw.worldDir, - this.mw.worldDir.getName())); - - Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); - } - - public void regenerateView() { - Utils.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ())); - //this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask( - this.mw, - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch(key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, - 0 - ); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen( - new MwGuiTeleportDialog( - this, - this.mw, - this.mapView, - this.mouseBlockX, - Config.defaultTeleportHeight, - this.mouseBlockZ - ) - ); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - //case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(Config.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) - { - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen( - new MwGuiDimensionDialog( - this, - this.mw, - this.mapView, - this.mapView.getDimension() - ) - ); - } else if (this.optionsLabel.posWithin(x, y)) - { - try - { - GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); - this.mc.displayGuiScreen(newScreen); - } - catch (Exception e) - { - Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); - } - - //this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - //this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - marker - ) - ); - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - //this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { - //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - //this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); - Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); - } - } - - // called every frame - public void updateScreen() { - //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) { - String s; - if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); - } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); - } - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX,0, bZ)).isEmpty()) { - s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX,0, bZ)).biomeName); - } - } - - /*if (this.mw.markerManager.selectedMarker != null) { - s += ", current marker: " + this.mw.markerManager.selectedMarker.name; - }*/ - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); - this.drawCenteredString(this.fontRendererObj, - s, this.width / 2, this.height - 18, 0xffffff); - } - - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max( - this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, - title, - x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, - desc, - x + 10, y + 4, 0xcccccc); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - //double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - //this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayNameString(), - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); - } - - super.drawScreen(mouseX, mouseY, f); - } -} - +package mapwriter.gui; + +import java.awt.Point; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Set; + +import mapwriter.Mw; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import mapwriter.util.VersionCheck; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiConfirmOpenLink; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +import com.google.common.collect.Sets; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + public MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private int exit = 0; + + private Label helpLabel; + private Label optionsLabel; + private Label dimensionLabel; + private Label groupLabel; + private Label overlayLabel; + private Label updateLabel; + public static MwGui instance; + + private static final Set PROTOCOLS = Sets.newHashSet(new String[] { "http", + "https" }); + private URI clickedLinkURI; + + class Label { + int x = 0, y = 0, w = 1, h = 12; + + public Label() { + } + + public void draw(int x, int y, String s) { + this.x = x; + this.y = y; + this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; + MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, + 0x80000000); + MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, + this.y + 2, 0xffffff); + } + + public void drawToRightOf(Label label, String s) { + this.draw(label.x + label.w + 5, label.y, s); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) + && (y <= (this.y + this.h)); + } + } + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(); + this.mapView = new MapView(this.mw, true); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + + this.helpLabel = new Label(); + this.optionsLabel = new Label(); + this.dimensionLabel = new Label(); + this.groupLabel = new Label(); + this.overlayLabel = new Label(); + this.updateLabel = new Label(); + + instance = this; + } + + public MwGui(Mw mw, int dim, int x, int z) { + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() { + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) { + + } + + public void exitGui() { + // MwUtil.log("closing GUI"); + // set the mini map dimension to the GUI map dimension when closing + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + this.mc.getSoundHandler().resumeSounds(); + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click + // closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); + if ((worldDimension == this.mapView.getDimension()) + && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + // MwUtil.log("deleting marker %s", + // this.mw.markerManager.selectedMarker.name); + this.mw.markerManager + .delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir + .getName())); + + Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + + "'"); + } + + public void regenerateView() { + Utils.printBoth(String.format( + "regenerating %dx%d blocks starting from (%d, %d)", + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); + // this.mw.reloadBlockColours(); + this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch (key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, 0); + } + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, + this.mapView, this.mouseBlockX, + Config.defaultTeleportHeight, this.mouseBlockZ)); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + // case Keyboard.KEY_9: + // MwUtil.log("refreshing maptexture"); + // this.mw.mapTexture.updateTexture(); + // break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + // exit on the next tick + this.exit = 1; + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(Config.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (MwAPI.getCurrentDataProvider() != null + && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, + this.mapMode)) + return; + + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height + / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) { + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, + this.mw, this.mapView, this.mapView.getDimension())); + } else if (this.optionsLabel.posWithin(x, y)) { + try { + GuiScreen newScreen = ModGuiConfig.class.getConstructor( + GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } catch (Exception e) { + Logging.logError( + "There was a critical issue trying to build the config GUI for %s", + Reference.MOD_ID); + } + + // this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else if (this.updateLabel.posWithin(x, y)) { + URI uri; + + if (!this.mc.gameSettings.chatLinks) { + return; + } + + try { + uri = new URI(VersionCheck.getUpdateURL()); + + if (!PROTOCOLS.contains(uri.getScheme().toLowerCase())) { + throw new URISyntaxException(uri.toString(), + "Unsupported protocol: " + + uri.getScheme().toLowerCase()); + } + + if (this.mc.gameSettings.chatLinksPrompt) { + this.clickedLinkURI = uri; + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, + uri.toString(), 31102009, false)); + } else { + Utils.openWebLink(uri); + } + } catch (URISyntaxException urisyntaxexception) { + Logging.logError("Can\'t open url for %s", + urisyntaxexception); + } + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + // this.mouseRightHeld = 1; + if ((marker != null) && (prevMarker == marker)) { + // right clicked previously selected marker. + // edit the marker + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, marker)); + + } else if (marker == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(x, y)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY + : Config.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, "", group, mx, my, mz, + this.mapView.getDimension())); + } + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, + y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), + blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + // this.viewSizeStart = this.mapManager.getViewSize(); + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseReleased(int x, int y, int button) { + // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + // this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) + && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, + n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated( + this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, + this.mouseBlockX, this.mouseBlockZ); + Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); + } + } + + // called every frame + public void updateScreen() { + // MwUtil.log("MwGui.updateScreen() " + + // Thread.currentThread().getName()); + // need to wait one tick before exiting so that the game doesn't + // handle the 'm' key and re-open the gui. + // there should be a better way. + if (this.exit > 0) { + this.exit++; + } + if (this.exit > 2) { + this.exitGui(); + } + super.updateScreen(); + } + + public void drawStatus(int bX, int bY, int bZ) { + String s; + if (bY != 0) { + s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + } else { + s = String.format("cursor: (%d, ?, %d)", bX, bZ); + } + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords( + new BlockPos(bX, 0, bZ)).isEmpty()) { + s += String.format(", biome: %s", + this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, + 0, bZ)).biomeName); + } + } + + /* + * if (this.mw.markerManager.selectedMarker != null) { s += + * ", current marker: " + this.mw.markerManager.selectedMarker.name; } + */ + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + s += provider.getStatusString(this.mapView.getDimension(), bX, bY, + bZ); + + drawRect(10, this.height - 21, this.width - 20, this.height - 6, + 0x80000000); + this.drawCenteredString(this.fontRendererObj, s, this.width / 2, + this.height - 18, 0xffffff); + } + + //TODO: Make this more generic in the label class + //TODO: Make the rectangle not fill whole screen, look at player info hover. + public void drawHelp() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString( + "Keys:\n\n" + + " Space\n" + + " Delete\n" + + " C\n" + + " Home\n" + + " End\n" + + " N\n" + + " T\n" + + " P\n" + + " R\n" + + " U\n\n" + + + "Left click drag or arrow keys pan the map.\n" + + "Mouse wheel or Page Up/Down zooms map.\n" + + "Right click map to create a new marker.\n" + + "Left click drag a selected marker to move it.\n" + + "Mouse wheel over selected marker to cycle colour.\n" + + "Mouse wheel over dimension or group box to cycle.\n", + 15, 24, this.width - 30, 0xffffff); + this.fontRendererObj.drawSplitString( + "| Next marker group\n" + + "| Delete selected marker\n" + + "| Cycle selected marker colour\n" + + "| Centre map on player\n" + + "| Centre map on selected marker\n" + + "| Select next marker\n" + + "| Teleport to cursor or selected marker\n" + + "| Save PNG of visible map area\n" + + "| Regenerate visible map area from region files\n" + + "| Underground map mode\n", + 75, 42, this.width - 90, 0xffffff); + } + + public void drawUpdate() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString(VersionCheck.getUpdateURL(), 15, + 24, this.width - 30, 0xffffff); + } + + public void drawMouseOverHint(int x, int y, String title, int mX, int mY, + int mZ) { + String desc = String.format("(%d, %d, %d)", mX, mY, mZ); + int stringW = Math.max(this.fontRendererObj.getStringWidth(title), + this.fontRendererObj.getStringWidth(desc)); + + x = Math.min(x, this.width - (stringW + 16)); + y = Math.min(Math.max(10, y), this.height - 14); + + drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); + this.drawString(this.fontRendererObj, title, x + 10, y - 8, 0xffffff); + this.drawString(this.fontRendererObj, desc, x + 10, y + 4, 0xcccccc); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + // double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) + * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) + * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView + .getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart + - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart + - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, + this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + // this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, + this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, + marker.y, marker.z); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + this.drawMouseOverHint(mouseX, mouseY, + this.mc.thePlayer.getDisplayNameString(), + this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(menuX, menuY, "[help]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); + String dimString = String.format("[dimension: %d]", + this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + String groupString = String.format("[group: %s]", + this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + String overlayString = String.format("[overlay: %s]", + MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + + if (!VersionCheck.isLatestVersion()) { + String updateString = String.format("[New version : %s]", + VersionCheck.getLatestVersion()); + this.updateLabel.drawToRightOf(this.overlayLabel, updateString); + } + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + this.drawHelp(); + } + if (this.updateLabel.posWithin(mouseX, mouseY)) { + this.drawUpdate(); + } + + super.drawScreen(mouseX, mouseY, f); + } + + public void confirmClicked(boolean result, int id) { + if (id == 31102009) { + if (result) { + Utils.openWebLink(this.clickedLinkURI); + } + + this.clickedLinkURI = null; + this.mc.displayGuiScreen(this); + } + } +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 16577b7d..780ad533 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,38 +1,40 @@ -package mapwriter.util; - -import java.util.regex.Pattern; - -import net.minecraft.util.ResourceLocation; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public static final String catOptions = "options"; - public static final String catLargeMapConfig = "largemap"; - public static final String catSmallMapConfig = "smallmap"; - public static final String catFullMapConfig = "fullscreenmap"; - - public static final String PlayerTrailName = "player"; - - public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - - public static final String catWorld = "world"; - public static final String catMarkers = "markers"; - public static final String worldDirConfigName = "mapwriter.cfg"; - public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - -} +package mapwriter.util; + +import java.util.regex.Pattern; + +import net.minecraft.util.ResourceLocation; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/mapwriter/1.8/version.json"; + + public static final String catOptions = "options"; + public static final String catLargeMapConfig = "largemap"; + public static final String catSmallMapConfig = "smallmap"; + public static final String catFullMapConfig = "fullscreenmap"; + + public static final String PlayerTrailName = "player"; + + public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + + public static final String catWorld = "world"; + public static final String catMarkers = "markers"; + public static final String worldDirConfigName = "mapwriter.cfg"; + public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index bc11898d..35060b1f 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,227 +1,245 @@ -package mapwriter.util; - -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mapwriter.config.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return Reference.patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - //send an ingame chat message and console log - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - Logging.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } - - public static String getWorldName() { - String worldName; - - if (Minecraft.getMinecraft().isIntegratedServerRunning()) - { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - else - { - worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; - if (!Config.portNumberInWorldNameEnabled) - { - worldName = worldName.substring(0, worldName.indexOf(":")); - } - else - { - if(worldName.indexOf(":")==-1){//standard port is missing. Adding it - worldName += "_25565"; - } else { - worldName = worldName.replace(":", "_"); - } - } - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - /* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * @since 4.37 - * @author Jaroslav Tulach - */ - /* - * Create a typesafe copy of a raw map. - * @param rawMap an unchecked map - * @param keyType the desired supertype of the keys - * @param valueType the desired supertype of the values - * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, - * false to skip over such map entries (warnings may be logged) - * @return a typed map guaranteed to contain only keys and values assignable - * to the named types (or they may be null) - * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true - */ - @SuppressWarnings("rawtypes") - public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { - Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); - Iterator it = rawMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); - try { - m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); - } catch (ClassCastException x) { - if (strict) { - throw x; - } else { - System.out.println("not assignable"); - } - } - } - return m2; - } -} +package mapwriter.util; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mapwriter.config.Config; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiConfirmOpenLink; +import net.minecraft.event.ClickEvent; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + //send an ingame chat message and console log + public static void printBoth(String msg) { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } + + public static String getWorldName() { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + if(worldName.indexOf(":")==-1){//standard port is missing. Adding it + worldName += "_25565"; + } else { + worldName = worldName.replace(":", "_"); + } + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } + + public static void openWebLink(URI p_175282_1_) + { + try + { + Class oclass = Class.forName("java.awt.Desktop"); + Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); + oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {p_175282_1_}); + } + catch (Throwable throwable) + { + Logging.logError("Couldn\'t open link %s", throwable.getStackTrace().toString()); + } + } + + /* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * @since 4.37 + * @author Jaroslav Tulach + */ + /* + * Create a typesafe copy of a raw map. + * @param rawMap an unchecked map + * @param keyType the desired supertype of the keys + * @param valueType the desired supertype of the values + * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, + * false to skip over such map entries (warnings may be logged) + * @return a typed map guaranteed to contain only keys and values assignable + * to the named types (or they may be null) + * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true + */ + @SuppressWarnings("rawtypes") + public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { + Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); + Iterator it = rawMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry e = (Map.Entry) it.next(); + try { + m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); + } catch (ClassCastException x) { + if (strict) { + throw x; + } else { + System.out.println("not assignable"); + } + } + } + return m2; + } +} diff --git a/src/main/java/mapwriter/util/VersionCheck.java b/src/main/java/mapwriter/util/VersionCheck.java new file mode 100644 index 00000000..2491eb70 --- /dev/null +++ b/src/main/java/mapwriter/util/VersionCheck.java @@ -0,0 +1,78 @@ +package mapwriter.util; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import net.minecraftforge.fml.common.Loader; + +import org.apache.commons.io.IOUtils; + +public class VersionCheck implements Runnable { +//TODO: add https://github.com/Dynious/VersionChecker suport + private static boolean isLatestVersion = true; + private static String latestVersion = ""; + private static String updateURL = ""; + + /** + * @author jabelar + * @link + * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making + * -mod.html + */ + + @Override + public void run() { + InputStream in = null; + try { + in = new URL(Reference.VersionURL).openStream(); + } catch (MalformedURLException e) { + } catch (IOException e) { + } + + try { + List list = IOUtils.readLines(in); + int index = -1; + for (int i = 0; i < list.size(); i++) { + if (list.get(i) + .contains(Loader.instance().getMCVersionString())) { + index = i; + break; + } + } + + String version = list.get(index + 1); + version = version.replace("\"modVersion\":\"", ""); + version = version.replace("\",", ""); + version = version.replace(" ", ""); + latestVersion = version; + + String updateURL = list.get(index + 3); + updateURL = updateURL.replace("\"updateURL\":\"", ""); + updateURL = updateURL.replace("\",", ""); + updateURL = updateURL.replace(" ", ""); + this.updateURL = updateURL; + + isLatestVersion = Reference.VERSION.equals(version); + + int test = 0; + } catch (IOException e) { + } + + } + + public static boolean isLatestVersion() { + return isLatestVersion; + } + + public static String getLatestVersion() { + return latestVersion; + } + + public static String getUpdateURL() + { + return updateURL; + } +} From 6a3b5e80616c7278b117ba9420328d7d0d3ff6a5 Mon Sep 17 00:00:00 2001 From: Thijs Date: Mon, 20 Jul 2015 22:11:24 +0200 Subject: [PATCH 059/109] Cleanup added suport for VersionCheck --- .../java/mapwriter/forge/ClientProxy.java | 89 +- src/main/java/mapwriter/gui/MwGui.java | 1426 ++++++++--------- src/main/java/mapwriter/util/Utils.java | 487 +++--- .../java/mapwriter/util/VersionCheck.java | 154 +- 4 files changed, 1080 insertions(+), 1076 deletions(-) diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 38e146d0..9170b754 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -1,40 +1,49 @@ -package mapwriter.forge; - -import java.io.File; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.config.ConfigurationHandler; -import mapwriter.overlay.OverlayGrid; -import mapwriter.overlay.OverlaySlime; -import mapwriter.util.VersionCheck; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.FMLCommonHandler; - -public class ClientProxy extends CommonProxy { - - public void preInit(File configFile) - { - ConfigurationHandler.init(configFile); - FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); - } - - public void load() { - EventHandler eventHandler = new EventHandler(Mw.getInstance()); - MinecraftForge.EVENT_BUS.register(eventHandler); - FMLCommonHandler.instance().bus().register(eventHandler); - - MwKeyHandler keyEventHandler = new MwKeyHandler(); - FMLCommonHandler.instance().bus().register(keyEventHandler); - MinecraftForge.EVENT_BUS.register(keyEventHandler); - } - - public void postInit() { - VersionCheck versionCheck = new VersionCheck(); - Thread versionCheckThread = new Thread(versionCheck, "Version Check"); - versionCheckThread.start(); - - MwAPI.registerDataProvider("Slime", new OverlaySlime()); - MwAPI.registerDataProvider("Grid", new OverlayGrid()); - } -} +package mapwriter.forge; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.config.ConfigurationHandler; +import mapwriter.overlay.OverlayGrid; +import mapwriter.overlay.OverlaySlime; +import mapwriter.util.Reference; +import mapwriter.util.VersionCheck; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.event.FMLInterModComms; + +public class ClientProxy extends CommonProxy { + + public void preInit(File configFile) + { + ConfigurationHandler.init(configFile); + FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); + } + + public void load() { + EventHandler eventHandler = new EventHandler(Mw.getInstance()); + MinecraftForge.EVENT_BUS.register(eventHandler); + FMLCommonHandler.instance().bus().register(eventHandler); + + MwKeyHandler keyEventHandler = new MwKeyHandler(); + FMLCommonHandler.instance().bus().register(keyEventHandler); + MinecraftForge.EVENT_BUS.register(keyEventHandler); + } + + public void postInit() { + if (Loader.isModLoaded("VersionChecker")) + { + FMLInterModComms.sendRuntimeMessage(Reference.MOD_ID, "VersionChecker", "addVersionCheck", Reference.VersionURL); + } + else + { + VersionCheck versionCheck = new VersionCheck(); + Thread versionCheckThread = new Thread(versionCheck, "Version Check"); + versionCheckThread.start(); + } + MwAPI.registerDataProvider("Slime", new OverlaySlime()); + MwAPI.registerDataProvider("Grid", new OverlayGrid()); + } +} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 338e62c5..e2447db9 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,713 +1,713 @@ -package mapwriter.gui; - -import java.awt.Point; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Set; - -import mapwriter.Mw; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import mapwriter.util.VersionCheck; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.util.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -import com.google.common.collect.Sets; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - public MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - private Label updateLabel; - public static MwGui instance; - - private static final Set PROTOCOLS = Sets.newHashSet(new String[] { "http", - "https" }); - private URI clickedLinkURI; - - class Label { - int x = 0, y = 0, w = 1, h = 12; - - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, - 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, - this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) - && (y <= (this.y + this.h)); - } - } - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw, true); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - this.updateLabel = new Label(); - - instance = this; - } - - public MwGui(Mw mw, int dim, int x, int z) { - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - public void exitGui() { - // MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click - // closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) - && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - // MwUtil.log("deleting marker %s", - // this.mw.markerManager.selectedMarker.name); - this.mw.markerManager - .delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir - .getName())); - - Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() - + "'"); - } - - public void regenerateView() { - Utils.printBoth(String.format( - "regenerating %dx%d blocks starting from (%d, %d)", - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); - // this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch (key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, 0); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, - this.mapView, this.mouseBlockX, - Config.defaultTeleportHeight, this.mouseBlockZ)); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - // case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(Config.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null - && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, - this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height - / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) { - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, - this.mw, this.mapView, this.mapView.getDimension())); - } else if (this.optionsLabel.posWithin(x, y)) { - try { - GuiScreen newScreen = ModGuiConfig.class.getConstructor( - GuiScreen.class).newInstance(this); - this.mc.displayGuiScreen(newScreen); - } catch (Exception e) { - Logging.logError( - "There was a critical issue trying to build the config GUI for %s", - Reference.MOD_ID); - } - - // this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else if (this.updateLabel.posWithin(x, y)) { - URI uri; - - if (!this.mc.gameSettings.chatLinks) { - return; - } - - try { - uri = new URI(VersionCheck.getUpdateURL()); - - if (!PROTOCOLS.contains(uri.getScheme().toLowerCase())) { - throw new URISyntaxException(uri.toString(), - "Unsupported protocol: " - + uri.getScheme().toLowerCase()); - } - - if (this.mc.gameSettings.chatLinksPrompt) { - this.clickedLinkURI = uri; - this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, - uri.toString(), 31102009, false)); - } else { - Utils.openWebLink(uri); - } - } catch (URISyntaxException urisyntaxexception) { - Logging.logError("Can\'t open url for %s", - urisyntaxexception); - } - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - // this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, marker)); - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY - : Config.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, "", group, mx, my, mz, - this.mapView.getDimension())); - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, - y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), - blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - // this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { - // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - // this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) - && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, - n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated( - this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, - this.mouseBlockX, this.mouseBlockZ); - Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); - } - } - - // called every frame - public void updateScreen() { - // MwUtil.log("MwGui.updateScreen() " + - // Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) { - String s; - if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); - } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); - } - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords( - new BlockPos(bX, 0, bZ)).isEmpty()) { - s += String.format(", biome: %s", - this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, - 0, bZ)).biomeName); - } - } - - /* - * if (this.mw.markerManager.selectedMarker != null) { s += - * ", current marker: " + this.mw.markerManager.selectedMarker.name; } - */ - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, - bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, - 0x80000000); - this.drawCenteredString(this.fontRendererObj, s, this.width / 2, - this.height - 18, 0xffffff); - } - - //TODO: Make this more generic in the label class - //TODO: Make the rectangle not fill whole screen, look at player info hover. - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawUpdate() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString(VersionCheck.getUpdateURL(), 15, - 24, this.width - 30, 0xffffff); - } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, - int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max(this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, title, x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, desc, x + 10, y + 4, 0xcccccc); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - // double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) - * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) - * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView - .getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, - this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - // this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, - this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, - marker.y, marker.z); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, - this.mc.thePlayer.getDisplayNameString(), - this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", - this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", - this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay: %s]", - MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); - - if (!VersionCheck.isLatestVersion()) { - String updateString = String.format("[New version : %s]", - VersionCheck.getLatestVersion()); - this.updateLabel.drawToRightOf(this.overlayLabel, updateString); - } - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); - } - if (this.updateLabel.posWithin(mouseX, mouseY)) { - this.drawUpdate(); - } - - super.drawScreen(mouseX, mouseY, f); - } - - public void confirmClicked(boolean result, int id) { - if (id == 31102009) { - if (result) { - Utils.openWebLink(this.clickedLinkURI); - } - - this.clickedLinkURI = null; - this.mc.displayGuiScreen(this); - } - } -} +package mapwriter.gui; + +import java.awt.Point; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashSet; + +import mapwriter.Mw; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import mapwriter.util.VersionCheck; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiConfirmOpenLink; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +import com.google.common.collect.Sets; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + public MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private int exit = 0; + + private Label helpLabel; + private Label optionsLabel; + private Label dimensionLabel; + private Label groupLabel; + private Label overlayLabel; + private Label updateLabel; + public static MwGui instance; + + private static final HashSet PROTOCOLS = Sets.newHashSet(new String[] { "http", + "https" }); + private URI clickedLinkURI; + + class Label { + int x = 0, y = 0, w = 1, h = 12; + + public Label() { + } + + public void draw(int x, int y, String s) { + this.x = x; + this.y = y; + this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; + MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, + 0x80000000); + MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, + this.y + 2, 0xffffff); + } + + public void drawToRightOf(Label label, String s) { + this.draw(label.x + label.w + 5, label.y, s); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) + && (y <= (this.y + this.h)); + } + } + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(); + this.mapView = new MapView(this.mw, true); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + + this.helpLabel = new Label(); + this.optionsLabel = new Label(); + this.dimensionLabel = new Label(); + this.groupLabel = new Label(); + this.overlayLabel = new Label(); + this.updateLabel = new Label(); + + instance = this; + } + + public MwGui(Mw mw, int dim, int x, int z) { + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() { + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) { + + } + + public void exitGui() { + // MwUtil.log("closing GUI"); + // set the mini map dimension to the GUI map dimension when closing + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + this.mc.getSoundHandler().resumeSounds(); + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click + // closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); + if ((worldDimension == this.mapView.getDimension()) + && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + // MwUtil.log("deleting marker %s", + // this.mw.markerManager.selectedMarker.name); + this.mw.markerManager + .delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir + .getName())); + + Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + + "'"); + } + + public void regenerateView() { + Utils.printBoth(String.format( + "regenerating %dx%d blocks starting from (%d, %d)", + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); + // this.mw.reloadBlockColours(); + this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch (key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, 0); + } + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, + this.mapView, this.mouseBlockX, + Config.defaultTeleportHeight, this.mouseBlockZ)); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + // case Keyboard.KEY_9: + // MwUtil.log("refreshing maptexture"); + // this.mw.mapTexture.updateTexture(); + // break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + // exit on the next tick + this.exit = 1; + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(Config.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (MwAPI.getCurrentDataProvider() != null + && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, + this.mapMode)) + return; + + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height + / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) { + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, + this.mw, this.mapView, this.mapView.getDimension())); + } else if (this.optionsLabel.posWithin(x, y)) { + try { + GuiScreen newScreen = ModGuiConfig.class.getConstructor( + GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } catch (Exception e) { + Logging.logError( + "There was a critical issue trying to build the config GUI for %s", + Reference.MOD_ID); + } + + // this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else if (this.updateLabel.posWithin(x, y)) { + URI uri; + + if (!this.mc.gameSettings.chatLinks) { + return; + } + + try { + uri = new URI(VersionCheck.getUpdateURL()); + + if (!PROTOCOLS.contains(uri.getScheme().toLowerCase())) { + throw new URISyntaxException(uri.toString(), + "Unsupported protocol: " + + uri.getScheme().toLowerCase()); + } + + if (this.mc.gameSettings.chatLinksPrompt) { + this.clickedLinkURI = uri; + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, + uri.toString(), 31102009, false)); + } else { + Utils.openWebLink(uri); + } + } catch (URISyntaxException urisyntaxexception) { + Logging.logError("Can\'t open url for %s", + urisyntaxexception); + } + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + // this.mouseRightHeld = 1; + if ((marker != null) && (prevMarker == marker)) { + // right clicked previously selected marker. + // edit the marker + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, marker)); + + } else if (marker == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(x, y)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY + : Config.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, "", group, mx, my, mz, + this.mapView.getDimension())); + } + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, + y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), + blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + // this.viewSizeStart = this.mapManager.getViewSize(); + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseReleased(int x, int y, int button) { + // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + // this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) + && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, + n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated( + this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, + this.mouseBlockX, this.mouseBlockZ); + Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); + } + } + + // called every frame + public void updateScreen() { + // MwUtil.log("MwGui.updateScreen() " + + // Thread.currentThread().getName()); + // need to wait one tick before exiting so that the game doesn't + // handle the 'm' key and re-open the gui. + // there should be a better way. + if (this.exit > 0) { + this.exit++; + } + if (this.exit > 2) { + this.exitGui(); + } + super.updateScreen(); + } + + public void drawStatus(int bX, int bY, int bZ) { + String s; + if (bY != 0) { + s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + } else { + s = String.format("cursor: (%d, ?, %d)", bX, bZ); + } + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords( + new BlockPos(bX, 0, bZ)).isEmpty()) { + s += String.format(", biome: %s", + this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, + 0, bZ)).biomeName); + } + } + + /* + * if (this.mw.markerManager.selectedMarker != null) { s += + * ", current marker: " + this.mw.markerManager.selectedMarker.name; } + */ + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + s += provider.getStatusString(this.mapView.getDimension(), bX, bY, + bZ); + + drawRect(10, this.height - 21, this.width - 20, this.height - 6, + 0x80000000); + this.drawCenteredString(this.fontRendererObj, s, this.width / 2, + this.height - 18, 0xffffff); + } + + //TODO: Make this more generic in the label class + //TODO: Make the rectangle not fill whole screen, look at player info hover. + public void drawHelp() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString( + "Keys:\n\n" + + " Space\n" + + " Delete\n" + + " C\n" + + " Home\n" + + " End\n" + + " N\n" + + " T\n" + + " P\n" + + " R\n" + + " U\n\n" + + + "Left click drag or arrow keys pan the map.\n" + + "Mouse wheel or Page Up/Down zooms map.\n" + + "Right click map to create a new marker.\n" + + "Left click drag a selected marker to move it.\n" + + "Mouse wheel over selected marker to cycle colour.\n" + + "Mouse wheel over dimension or group box to cycle.\n", + 15, 24, this.width - 30, 0xffffff); + this.fontRendererObj.drawSplitString( + "| Next marker group\n" + + "| Delete selected marker\n" + + "| Cycle selected marker colour\n" + + "| Centre map on player\n" + + "| Centre map on selected marker\n" + + "| Select next marker\n" + + "| Teleport to cursor or selected marker\n" + + "| Save PNG of visible map area\n" + + "| Regenerate visible map area from region files\n" + + "| Underground map mode\n", + 75, 42, this.width - 90, 0xffffff); + } + + public void drawUpdate() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString(VersionCheck.getUpdateURL(), 15, + 24, this.width - 30, 0xffffff); + } + + public void drawMouseOverHint(int x, int y, String title, int mX, int mY, + int mZ) { + String desc = String.format("(%d, %d, %d)", mX, mY, mZ); + int stringW = Math.max(this.fontRendererObj.getStringWidth(title), + this.fontRendererObj.getStringWidth(desc)); + + x = Math.min(x, this.width - (stringW + 16)); + y = Math.min(Math.max(10, y), this.height - 14); + + drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); + this.drawString(this.fontRendererObj, title, x + 10, y - 8, 0xffffff); + this.drawString(this.fontRendererObj, desc, x + 10, y + 4, 0xcccccc); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + // double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) + * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) + * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView + .getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart + - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart + - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, + this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + // this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, + this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, + marker.y, marker.z); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + this.drawMouseOverHint(mouseX, mouseY, + this.mc.thePlayer.getDisplayNameString(), + this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(menuX, menuY, "[help]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); + String dimString = String.format("[dimension: %d]", + this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + String groupString = String.format("[group: %s]", + this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + String overlayString = String.format("[overlay: %s]", + MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + + if (!VersionCheck.isLatestVersion()) { + String updateString = String.format("[New version : %s]", + VersionCheck.getLatestVersion()); + this.updateLabel.drawToRightOf(this.overlayLabel, updateString); + } + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + this.drawHelp(); + } + if (this.updateLabel.posWithin(mouseX, mouseY)) { + this.drawUpdate(); + } + + super.drawScreen(mouseX, mouseY, f); + } + + public void confirmClicked(boolean result, int id) { + if (id == 31102009) { + if (result) { + Utils.openWebLink(this.clickedLinkURI); + } + + this.clickedLinkURI = null; + this.mc.displayGuiScreen(this); + } + } +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 35060b1f..439706a4 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,245 +1,242 @@ -package mapwriter.util; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mapwriter.config.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.event.ClickEvent; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return Reference.patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - //send an ingame chat message and console log - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - Logging.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } - - public static String getWorldName() { - String worldName; - - if (Minecraft.getMinecraft().isIntegratedServerRunning()) - { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - else - { - worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; - if (!Config.portNumberInWorldNameEnabled) - { - worldName = worldName.substring(0, worldName.indexOf(":")); - } - else - { - if(worldName.indexOf(":")==-1){//standard port is missing. Adding it - worldName += "_25565"; - } else { - worldName = worldName.replace(":", "_"); - } - } - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - public static void openWebLink(URI p_175282_1_) - { - try - { - Class oclass = Class.forName("java.awt.Desktop"); - Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); - oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {p_175282_1_}); - } - catch (Throwable throwable) - { - Logging.logError("Couldn\'t open link %s", throwable.getStackTrace().toString()); - } - } - - /* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * @since 4.37 - * @author Jaroslav Tulach - */ - /* - * Create a typesafe copy of a raw map. - * @param rawMap an unchecked map - * @param keyType the desired supertype of the keys - * @param valueType the desired supertype of the values - * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, - * false to skip over such map entries (warnings may be logged) - * @return a typed map guaranteed to contain only keys and values assignable - * to the named types (or they may be null) - * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true - */ - @SuppressWarnings("rawtypes") - public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { - Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); - Iterator it = rawMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); - try { - m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); - } catch (ClassCastException x) { - if (strict) { - throw x; - } else { - System.out.println("not assignable"); - } - } - } - return m2; - } -} +package mapwriter.util; + +import java.io.File; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mapwriter.config.Config; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + //send an ingame chat message and console log + public static void printBoth(String msg) { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } + + public static String getWorldName() { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + if(worldName.indexOf(":")==-1){//standard port is missing. Adding it + worldName += "_25565"; + } else { + worldName = worldName.replace(":", "_"); + } + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } + + public static void openWebLink(URI p_175282_1_) + { + try + { + Class oclass = Class.forName("java.awt.Desktop"); + Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); + oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {p_175282_1_}); + } + catch (Throwable throwable) + { + Logging.logError("Couldn\'t open link %s", throwable.getStackTrace().toString()); + } + } + + /* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * @since 4.37 + * @author Jaroslav Tulach + */ + /* + * Create a typesafe copy of a raw map. + * @param rawMap an unchecked map + * @param keyType the desired supertype of the keys + * @param valueType the desired supertype of the values + * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, + * false to skip over such map entries (warnings may be logged) + * @return a typed map guaranteed to contain only keys and values assignable + * to the named types (or they may be null) + * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true + */ + @SuppressWarnings("rawtypes") + public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { + Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); + Iterator it = rawMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry e = (Map.Entry) it.next(); + try { + m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); + } catch (ClassCastException x) { + if (strict) { + throw x; + } else { + System.out.println("not assignable"); + } + } + } + return m2; + } +} diff --git a/src/main/java/mapwriter/util/VersionCheck.java b/src/main/java/mapwriter/util/VersionCheck.java index 2491eb70..992c1b4e 100644 --- a/src/main/java/mapwriter/util/VersionCheck.java +++ b/src/main/java/mapwriter/util/VersionCheck.java @@ -1,78 +1,76 @@ -package mapwriter.util; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import net.minecraftforge.fml.common.Loader; - -import org.apache.commons.io.IOUtils; - -public class VersionCheck implements Runnable { -//TODO: add https://github.com/Dynious/VersionChecker suport - private static boolean isLatestVersion = true; - private static String latestVersion = ""; - private static String updateURL = ""; - - /** - * @author jabelar - * @link - * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making - * -mod.html - */ - - @Override - public void run() { - InputStream in = null; - try { - in = new URL(Reference.VersionURL).openStream(); - } catch (MalformedURLException e) { - } catch (IOException e) { - } - - try { - List list = IOUtils.readLines(in); - int index = -1; - for (int i = 0; i < list.size(); i++) { - if (list.get(i) - .contains(Loader.instance().getMCVersionString())) { - index = i; - break; - } - } - - String version = list.get(index + 1); - version = version.replace("\"modVersion\":\"", ""); - version = version.replace("\",", ""); - version = version.replace(" ", ""); - latestVersion = version; - - String updateURL = list.get(index + 3); - updateURL = updateURL.replace("\"updateURL\":\"", ""); - updateURL = updateURL.replace("\",", ""); - updateURL = updateURL.replace(" ", ""); - this.updateURL = updateURL; - - isLatestVersion = Reference.VERSION.equals(version); - - int test = 0; - } catch (IOException e) { - } - - } - - public static boolean isLatestVersion() { - return isLatestVersion; - } - - public static String getLatestVersion() { - return latestVersion; - } - - public static String getUpdateURL() - { - return updateURL; - } -} +package mapwriter.util; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import net.minecraftforge.fml.common.Loader; + +import org.apache.commons.io.IOUtils; + +public class VersionCheck implements Runnable { +//TODO: add https://github.com/Dynious/VersionChecker suport + private static boolean isLatestVersion = true; + private static String latestVersion = ""; + private static String updateURL = ""; + + /** + * @author jabelar + * @link + * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making + * -mod.html + */ + + @Override + public void run() { + InputStream in = null; + try { + in = new URL(Reference.VersionURL).openStream(); + } catch (MalformedURLException e) { + } catch (IOException e) { + } + + try { + List list = IOUtils.readLines(in); + int index = -1; + for (int i = 0; i < list.size(); i++) { + if (list.get(i) + .contains(Loader.instance().getMCVersionString())) { + index = i; + break; + } + } + + String version = list.get(index + 1); + version = version.replace("\"modVersion\":\"", ""); + version = version.replace("\",", ""); + version = version.replace(" ", ""); + latestVersion = version; + + String updateURL = list.get(index + 3); + updateURL = updateURL.replace("\"updateURL\":\"", ""); + updateURL = updateURL.replace("\",", ""); + updateURL = updateURL.replace(" ", ""); + VersionCheck.updateURL = updateURL; + + isLatestVersion = Reference.VERSION.equals(version); + } catch (IOException e) { + } + + } + + public static boolean isLatestVersion() { + return isLatestVersion; + } + + public static String getLatestVersion() { + return latestVersion; + } + + public static String getUpdateURL() + { + return updateURL; + } +} From e7f6033ffc940f234ca9b7347bb4a03b58367075 Mon Sep 17 00:00:00 2001 From: Thijs Date: Mon, 20 Jul 2015 22:27:18 +0200 Subject: [PATCH 060/109] Moved version file to own repo. --- src/main/java/mapwriter/util/Reference.java | 80 ++++++++++----------- version.json | 20 ------ 2 files changed, 40 insertions(+), 60 deletions(-) delete mode 100644 version.json diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 780ad533..e123b919 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,40 +1,40 @@ -package mapwriter.util; - -import java.util.regex.Pattern; - -import net.minecraft.util.ResourceLocation; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/mapwriter/1.8/version.json"; - - public static final String catOptions = "options"; - public static final String catLargeMapConfig = "largemap"; - public static final String catSmallMapConfig = "smallmap"; - public static final String catFullMapConfig = "fullscreenmap"; - - public static final String PlayerTrailName = "player"; - - public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - - public static final String catWorld = "world"; - public static final String catMarkers = "markers"; - public static final String worldDirConfigName = "mapwriter.cfg"; - public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - -} +package mapwriter.util; + +import java.util.regex.Pattern; + +import net.minecraft.util.ResourceLocation; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/Versions/master/MwVersion.json"; + + public static final String catOptions = "options"; + public static final String catLargeMapConfig = "largemap"; + public static final String catSmallMapConfig = "smallmap"; + public static final String catFullMapConfig = "fullscreenmap"; + + public static final String PlayerTrailName = "player"; + + public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + + public static final String catWorld = "world"; + public static final String catMarkers = "markers"; + public static final String worldDirConfigName = "mapwriter.cfg"; + public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + +} diff --git a/version.json b/version.json deleted file mode 100644 index e36bf5ad..00000000 --- a/version.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "versionList": [ - { - "mcVersion":"Minecraft 1.7.10", - "modVersion":"2.1.5", - "changeLog": [], - "updateURL":"http://minecraft.curseforge.com/mc-mods/231387-mapwriter-2/files/", - "isDirectLink":"false", - "newFileName":"" - }, - { - "mcVersion":"Minecraft 1.8", - "modVersion":"2.2.5", - "changeLog": [], - "updateURL":"http://minecraft.curseforge.com/mc-mods/231387-mapwriter-2/files/", - "isDirectLink":"false", - "newFileName":"" - } - ] -} \ No newline at end of file From 6b4fc66ad94ecc0a0c56d35b40dc0ef9282c1f93 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 15:31:18 +0200 Subject: [PATCH 061/109] add strings to localization --- src/main/java/mapwriter/config/Config.java | 2 +- .../config/ConfigurationHandler.java | 4 +- src/main/java/mapwriter/gui/MwGui.java | 73 +++++++++++-------- .../mapwriter/gui/MwGuiDimensionDialog.java | 6 +- .../java/mapwriter/gui/MwGuiMarkerDialog.java | 31 +++++--- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 33 +++++---- .../mapwriter/gui/MwGuiTeleportDialog.java | 6 +- .../assets/mapwriter/lang/en_US.lang | 67 ++++++++++++++++- 8 files changed, 160 insertions(+), 62 deletions(-) diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 9edb3c46..47a3cb8b 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -48,7 +48,7 @@ public class Config { public static String backgroundTextureMode = backgroundTextureModeDef; public static boolean moreRealisticMapDef = false; public static boolean moreRealisticMap = moreRealisticMapDef; - public static boolean newMarkerDialogDef = false; + public static boolean newMarkerDialogDef = true; public static boolean newMarkerDialog = newMarkerDialogDef; diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 8c1e3b33..fec469b9 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -38,7 +38,7 @@ public static void loadConfig() Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureModeDef", Config.backgroundModeStringArray); + Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureMode", Config.backgroundModeStringArray); Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); @@ -50,7 +50,7 @@ public static void loadConfig() Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "mw.config.newMarkerDialog"); - + Config.fullScreenMap.loadConfig(); Config.largeMap.loadConfig(); Config.smallMap.loadConfig(); diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 56d787f8..ef562eb7 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -26,6 +26,7 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiConfirmOpenLink; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; import net.minecraft.util.BlockPos; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -197,13 +198,16 @@ public void mergeMapViewToImage() { this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir .getName())); - Utils.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() + "'"); } public void regenerateView() { Utils.printBoth(String.format( - "regenerating %dx%d blocks starting from (%d, %d)", + I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + + " %dx%d " + + I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + + " (%d, %d)", (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); // this.mw.reloadBlockColours(); @@ -404,14 +408,25 @@ protected void mouseClicked(int x, int y, int button) { if ((marker != null) && (prevMarker == marker)) { // right clicked previously selected marker. // edit the marker + if (Config.newMarkerDialog) + { + this.mc.displayGuiScreen( + new MwGuiMarkerDialogNew(this, + this.mw.markerManager, marker + ) + ); + } + else + { this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, this.mw.markerManager, marker)); + } } else if (marker == null) { // open new marker dialog String group = this.mw.markerManager.getVisibleGroupName(); if (group.equals("none")) { - group = "group"; + group = I18n.format("mw.gui.mwgui.group", new Object[0]); } int mx, my, mz; @@ -521,7 +536,7 @@ public void mouseDWheelScrolled(int x, int y, int direction) { // called every frame public void updateScreen() { - // MwUtil.log("MwGui.updateScreen() " + + // TODO:MwUtil.log("MwGui.updateScreen() " + // Thread.currentThread().getName()); // need to wait one tick before exiting so that the game doesn't // handle the 'm' key and re-open the gui. @@ -538,14 +553,14 @@ public void updateScreen() { public void drawStatus(int bX, int bY, int bZ) { String s; if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + s = String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ); } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); + s = String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ); } if (this.mc.theWorld != null) { if (!this.mc.theWorld.getChunkFromBlockCoords( new BlockPos(bX, 0, bZ)).isEmpty()) { - s += String.format(", biome: %s", + s += String.format(", " + I18n.format("mw.gui.mwgui.status.biome", new Object[0]) + ": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName); } @@ -584,24 +599,24 @@ public void drawHelp() { " R\n" + " U\n\n" + - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", + I18n.format("mw.gui.mwgui.helptext.1", new Object[0]) + "\n" + + I18n.format("mw.gui.mwgui.helptext.2", new Object[0]) + "\n" + + I18n.format("mw.gui.mwgui.helptext.3", new Object[0]) + "\n" + + I18n.format("mw.gui.mwgui.helptext.4", new Object[0]) + "\n" + + I18n.format("mw.gui.mwgui.helptext.5", new Object[0]) + "\n" + + I18n.format("mw.gui.mwgui.helptext.6", new Object[0]) + "\n", 15, 24, this.width - 30, 0xffffff); this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", + "| " + I18n.format("mw.gui.mwgui.helptext.nextmarkergroup", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.deletemarker", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.cyclecolour", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.centermap", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.centermapplayer", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.selectnextmarker", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.teleport", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.savepng", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.regenerate", new Object[0]) + "\n" + + "| " + I18n.format("mw.gui.mwgui.helptext.undergroundmap", new Object[0]) + "\n", 75, 42, this.width - 90, 0xffffff); } @@ -687,20 +702,20 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", + this.helpLabel.draw(menuX, menuY, "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"); + String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", + String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay: %s]", + String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); if (!VersionCheck.isLatestVersion()) { - String updateString = String.format("[New version : %s]", + String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", VersionCheck.getLatestVersion()); this.updateLabel.drawToRightOf(this.overlayLabel, updateString); } diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java index 7dbf02c5..cb2277e4 100644 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -4,6 +4,7 @@ import mapwriter.config.WorldConfig; import mapwriter.map.MapView; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -15,7 +16,10 @@ public class MwGuiDimensionDialog extends MwGuiTextDialog { final int dimension; public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) { - super(parentScreen, "Set dimension to:", "" + dimension, "invalid dimension"); + super(parentScreen, + I18n.format("mw.gui.mwguidimensiondialog.title", new Object[0]) + ":", + Integer.toString(dimension), + I18n.format("mw.gui.mwguidimensiondialog.error", new Object[0])); this.mw = mw; this.mapView = mapView; this.dimension = dimension; diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java index 27eb6102..24e00fd8 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -3,6 +3,7 @@ import mapwriter.map.Marker; import mapwriter.map.MarkerManager; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -10,8 +11,8 @@ public class MwGuiMarkerDialog extends MwGuiTextDialog { private final MarkerManager markerManager; private Marker editingMarker; - private String markerName = "name"; - private String markerGroup = "group"; + private String markerName = ""; + private String markerGroup = ""; private int markerX = 0; private int markerY = 80; private int markerZ = 0; @@ -19,7 +20,10 @@ public class MwGuiMarkerDialog extends MwGuiTextDialog { private int dimension = 0; public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { - super(parentScreen, "Marker Name:", markerName, "marker must have a name"); + super(parentScreen, + I18n.format("mw.gui.mwguimarkerdialog.title.new", new Object[0]) + ":", + markerName, + I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); this.markerManager = markerManager; this.markerName = markerName; this.markerGroup = markerGroup; @@ -31,7 +35,10 @@ public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, St } public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) { - super(parentScreen, "Edit Marker Name:", editingMarker.name, "marker must have a name"); + super(parentScreen, + I18n.format("mw.gui.mwguimarkerdialog.title.edit", new Object[0]) + ":", + editingMarker.name, + I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); this.markerManager = markerManager; this.editingMarker = editingMarker; this.markerName = editingMarker.name; @@ -49,36 +56,36 @@ public boolean submit() { case 0: this.markerName = this.getInputAsString(); if (this.inputValid) { - this.title = "Marker Group:"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.group", new Object[0]) + ":"; this.setText(this.markerGroup); - this.error = "marker must have a group name"; + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.group", new Object[0]); this.state++; } break; case 1: this.markerGroup = this.getInputAsString(); if (this.inputValid) { - this.title = "Marker X:"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.x", new Object[0]) + ":"; this.setText("" + this.markerX); - this.error = "invalid value"; + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.x", new Object[0]); this.state++; } break; case 2: this.markerX = this.getInputAsInt(); if (this.inputValid) { - this.title = "Marker Y:"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.y", new Object[0]) + ":"; this.setText("" + this.markerY); - this.error = "invalid value"; + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.y", new Object[0]); this.state++; } break; case 3: this.markerY = this.getInputAsInt(); if (this.inputValid) { - this.title = "Marker Z:"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.z", new Object[0]) + ":"; this.setText("" + this.markerZ); - this.error = "invalid value"; + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.z", new Object[0]); this.state++; } break; diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index 4a63eb56..d983b3a3 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -9,6 +9,7 @@ import mapwriter.util.Render; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; @@ -18,12 +19,14 @@ @net.minecraftforge.fml.relauncher.SideOnly(Side.CLIENT) public class MwGuiMarkerDialogNew extends GuiScreen { private final GuiScreen parentScreen; - String title = "Add new marker"; - private String editMarkerName = "Name:"; - private String editMarkerGroup = "Group:"; - private String editMarkerX = "X:"; - private String editMarkerY = "Y:"; - private String editMarkerZ = "Z:"; + String title = ""; + String titleNew = "mw.gui.mwguimarkerdialognew.title.new"; + String titleEdit = "mw.gui.mwguimarkerdialognew.title.edit"; + private String editMarkerName = "mw.gui.mwguimarkerdialognew.editMarkerName"; + private String editMarkerGroup = "mw.gui.mwguimarkerdialognew.editMarkerGroup"; + private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; + private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; + private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; ScrollableTextBox scrollableTextBoxName = null; ScrollableTextBox scrollableTextBoxGroup = null; ScrollableNumericTextBox scrollableNumericTextBoxX = null; @@ -34,8 +37,8 @@ public class MwGuiMarkerDialogNew extends GuiScreen { static final int elementVSpacing = 20; private final MarkerManager markerManager; private Marker editingMarker; - private String markerName = "name"; - private String markerGroup = "none"; + private String markerName = ""; + private String markerGroup = ""; private int markerX = 0; private int markerY = 80; private int markerZ = 0; @@ -241,6 +244,7 @@ public MwGuiMarkerDialogNew(GuiScreen parentScreen, this.editingMarker = null; this.dimension = dimension; this.parentScreen = parentScreen; + this.title = this.titleNew; } public MwGuiMarkerDialogNew(GuiScreen parentScreen, @@ -254,6 +258,7 @@ public MwGuiMarkerDialogNew(GuiScreen parentScreen, this.markerZ = editingMarker.z; this.dimension = editingMarker.dimension; this.parentScreen = parentScreen; + this.title = this.titleEdit; } public boolean submit() { @@ -300,28 +305,28 @@ public void initGui() { int x = (this.width - width) / 2 + labelsWidth; int y = (this.height - elementVSpacing * 5) / 2; this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, - this.editMarkerName); + I18n.format(this.editMarkerName, new Object[0])); this.scrollableTextBoxName.init(); this.scrollableTextBoxName.textField.setFocused(true); this.scrollableTextBoxName.textField.setText(this.markerName); this.scrollableTextBoxGroup = new ScrollableTextBox(x, y - + this.elementVSpacing, width, this.editMarkerGroup, + + this.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), this.markerManager.groupList); this.scrollableTextBoxGroup.init(); this.scrollableTextBoxGroup.textField.setText(this.markerGroup); this.scrollableTextBoxGroup.setDrawArrows(true); this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 2, width, this.editMarkerX); + + this.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0])); this.scrollableNumericTextBoxX.init(); this.scrollableNumericTextBoxX.textField.setText("" + this.markerX); this.scrollableNumericTextBoxX.setDrawArrows(true); this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 3, width, this.editMarkerY); + + this.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0])); this.scrollableNumericTextBoxY.init(); this.scrollableNumericTextBoxY.textField.setText("" + this.markerY); this.scrollableNumericTextBoxY.setDrawArrows(true); this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 4, width, this.editMarkerZ); + + this.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0])); this.scrollableNumericTextBoxZ.init(); this.scrollableNumericTextBoxZ.textField.setText("" + this.markerZ); this.scrollableNumericTextBoxZ.setDrawArrows(true); @@ -344,7 +349,7 @@ public void drawScreen(int mouseX, int mouseY, float f) { 0x80000000); this.drawCenteredString( this.fontRendererObj, - this.title, + I18n.format(this.title, new Object[0]), (this.width) / 2, (this.height - this.elementVSpacing * 6) / 2 - this.elementVSpacing / 4, diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index bdb713e0..1ad8fe1e 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -4,6 +4,7 @@ import mapwriter.config.Config; import mapwriter.map.MapView; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -15,7 +16,10 @@ public class MwGuiTeleportDialog extends MwGuiTextDialog { final int teleportX, teleportZ; public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) { - super(parentScreen, "Teleport Height:", "" + y, "invalid height"); + super(parentScreen, + I18n.format("mw.gui.mwguimarkerdialognew.title", new Object[0]) + ":", + Integer.toString(y), + I18n.format("mw.gui.mwguimarkerdialognew.error", new Object[0])); this.mw = mw; this.mapView = mapView; this.teleportX = x; diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index 04d77008..f1c5d5ac 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -17,8 +17,7 @@ mw.config.teleportEnabled= Teleport enabled mw.config.teleportEnabled.tooltip=Enables teleporting to positions on the map mw.config.teleportCommand=Teleport Command mw.config.teleportCommand.tooltip=The command used to teleport the player -mw.config.coordsMode= Coordinates mode -mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap + mw.config.maxChunkSaveDistSq=Max draw distance mw.config.maxChunkSaveDistSq.tooltip=The square of the max distance from the player to map chunks at mw.config.mapPixelSnapEnabled= Map pixel snap @@ -47,6 +46,11 @@ mw.config.textureSize= mw.config.textureSize.tooltip= mw.config.moreRealisticMap=Enables realistic map mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic +mw.config.newMarkerDialog=New Marker Dialog +mw.config.newMarkerDialog.tooltip=Enable to use the new marker dialog +mw.config.useFeetHeight=Use feet height +mw.config.useFeetHeight.tooltip=Have cordinates show feet height instead of head height + #Config Temp mw.config.overlayModeIndex= @@ -83,3 +87,62 @@ mw.config.map.borderMode=Draw border mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map mw.config.map.trailMarkerSize=Trail marker size mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map + +mw.config.coordsMode= Coordinates mode +mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap + +#Gui +mw.gui.mwgui.help=Help +mw.gui.mwgui.options=Options +mw.gui.mwgui.dimension=dimension +mw.gui.mwgui.group=group +mw.gui.mwgui.overlay=overlay +mw.gui.mwgui.newversion=New version +mw.gui.mwgui.helptext.1=Left click drag or arrow keys pan the map. +mw.gui.mwgui.helptext.2=Mouse wheel or Page Up/Down zooms map. +mw.gui.mwgui.helptext.3=Right click map to create a new marker. +mw.gui.mwgui.helptext.4=Left click drag a selected marker to move it. +mw.gui.mwgui.helptext.5=Mouse wheel over selected marker to cycle colour. +mw.gui.mwgui.helptext.6=Mouse wheel over dimension or group box to cycle. +mw.gui.mwgui.helptext.nextmarkergroup=Next marker group +mw.gui.mwgui.helptext.deletemarker=Delete selected marker +mw.gui.mwgui.helptext.cyclecolour=Cycle selected marker colour +mw.gui.mwgui.helptext.centermap=Centre map on player +mw.gui.mwgui.helptext.centermapplayer=Centre map on selected marker +mw.gui.mwgui.helptext.selectnextmarker=Select next marker +mw.gui.mwgui.helptext.teleport=Teleport to cursor or selected marker +mw.gui.mwgui.helptext.savepng=Save PNG of visible map area +mw.gui.mwgui.helptext.regenerate=Regenerate visible map area from region files +mw.gui.mwgui.helptext.undergroundmap=Underground map mode +mw.gui.mwgui.status.biome=biome +mw.gui.mwgui.status.cursor=cursor +mw.gui.mwgui.chatmsg.regenmap.1=regenerating +mw.gui.mwgui.group=group +mw.gui.mwgui.chatmsg.regenmap.2=blocks starting from +mw.gui.mwgui.chatmsg.merge=merging to + +mw.gui.mwguidimensiondialog.title=Set dimension to +mw.gui.mwguidimensiondialog.error=invalid dimension + +mw.gui.mwguimarkerdialog.title.new=Marker Name +mw.gui.mwguimarkerdialog.title.edit=Edit Marker Name +mw.gui.mwguimarkerdialog.error=marker must have a name +mw.gui.mwguimarkerdialog.title.group=Marker Group +mw.gui.mwguimarkerdialog.error.group=marker must have a group name +mw.gui.mwguimarkerdialog.title.x=Marker X +mw.gui.mwguimarkerdialog.error.x=invalid value +mw.gui.mwguimarkerdialog.title.y=Marker Y +mw.gui.mwguimarkerdialog.error.y=invalid value +mw.gui.mwguimarkerdialog.title.z=Marker Z +mw.gui.mwguimarkerdialog.error.z=invalid value + +mw.gui.mwguimarkerdialognew.title.new=Add New Marker +mw.gui.mwguimarkerdialognew.title.edit=Edit Marker +mw.gui.mwguimarkerdialognew.editMarkerName=Name +mw.gui.mwguimarkerdialognew.editMarkerGroup=Group +mw.gui.mwguimarkerdialognew.editMarkerX=X +mw.gui.mwguimarkerdialognew.editMarkerY=Y +mw.gui.mwguimarkerdialognew.editMarkerZ=Z + +mw.gui.mwguimarkerdialognew.title=Teleport Height +mw.gui.mwguimarkerdialognew.error=invalid height \ No newline at end of file From 0b27b1fd19df204eb5606c872189f2dc4ae6504a Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:36:55 +0200 Subject: [PATCH 062/109] VersionChecker is suported --- src/main/java/mapwriter/util/VersionCheck.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/mapwriter/util/VersionCheck.java b/src/main/java/mapwriter/util/VersionCheck.java index 992c1b4e..46707db3 100644 --- a/src/main/java/mapwriter/util/VersionCheck.java +++ b/src/main/java/mapwriter/util/VersionCheck.java @@ -11,7 +11,6 @@ import org.apache.commons.io.IOUtils; public class VersionCheck implements Runnable { -//TODO: add https://github.com/Dynious/VersionChecker suport private static boolean isLatestVersion = true; private static String latestVersion = ""; private static String updateURL = ""; From a79bb18bdf3ef5f879f6a124d796798d4f0c0e0b Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:37:17 +0200 Subject: [PATCH 063/109] added Biomes o plenty blockstypes back --- .../java/mapwriter/region/BlockColours.java | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 8f0d0ca2..ac1ee4a0 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -560,20 +560,25 @@ public static void writeOverridesFile(File f) { + "blocktype minecraft:leaves 1 opaque # pine leaves (not biome colorized)\n" + "blocktype minecraft:leaves 2 opaque # birch leaves (not biome colorized)\n" + "blocktype minecraft:tallgrass * grass # tall grass block\n" - + "blocktype minecraft:vine * foliage # vines block\n"); + + "blocktype minecraft:vine * foliage # vines block\n" + + "blocktype BiomesOPlenty:grass * grass # BOP grass block\n" + + "blocktype BiomesOPlenty:plant_0 * grass # BOP plant block\n" + + "blocktype BiomesOPlenty:plant_1 * grass # BOP plant block\n" + + "blocktype BiomesOPlenty:leaves_0 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_1 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_2 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_3 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_4 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_5 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:tree_moss * foliage # biomes o plenty tree moss\n" + ); //TODO: Find out the names and readd these overwrites - // + "blocktype 169 * grass # biomes o plenty holy grass\n" - // + "blocktype 1920 * grass # biomes o plenty plant\n" - // + "blocktype 1923 * opaque # biomes o plenty leaves 1\n" - // + "blocktype 1924 * opaque # biomes o plenty leaves 2\n" - // + "blocktype 1925 * foliage # biomes o plenty foliage\n" - // + "blocktype 1926 * opaque # biomes o plenty fruit leaf block\n" - // + "blocktype 1932 * foliage # biomes o plenty tree moss\n" - // + "blocktype 1962 * leaves # biomes o plenty colorized leaves\n" // + "blocktype 2164 * leaves # twilight forest leaves\n" // + "blocktype 2177 * leaves # twilight forest magic leaves\n" + // + "blocktype 2204 * leaves # extrabiomesXL green leaves\n" // + "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + // + "blocktype 3257 * opaque # natura berry bush\n" // + "blocktype 3272 * opaque # natura darkwood leaves\n" // + "blocktype 3259 * leaves # natura flora leaves\n" From da94a12d2670c9ab145d5c21b3dedf7274de9deb Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:38:17 +0200 Subject: [PATCH 064/109] made draw tooltip more generic, and use it for all the information overlays. --- src/main/java/mapwriter/gui/MwGui.java | 245 +++++++++++++------------ 1 file changed, 130 insertions(+), 115 deletions(-) diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index ef562eb7..19842e11 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -43,6 +43,42 @@ public class MwGui extends GuiScreen { private MapView mapView; private MapRenderer map; + private String[] HelpText1 = new String[]{ + "Keys:", + "", + " Space", + " Delete", + " C", + " Home", + " End", + " N", + " T", + " P", + " R", + " U", + "", + "mw.gui.mwgui.helptext.1", + "mw.gui.mwgui.helptext.2", + "mw.gui.mwgui.helptext.3", + "mw.gui.mwgui.helptext.4", + "mw.gui.mwgui.helptext.5", + "mw.gui.mwgui.helptext.6" + }; + private String[] HelpText2 = new String[]{ + "", + "", + "mw.gui.mwgui.helptext.nextmarkergroup", + "mw.gui.mwgui.helptext.deletemarker", + "mw.gui.mwgui.helptext.cyclecolour", + "mw.gui.mwgui.helptext.centermap", + "mw.gui.mwgui.helptext.centermapplayer", + "mw.gui.mwgui.helptext.selectnextmarker", + "mw.gui.mwgui.helptext.teleport", + "mw.gui.mwgui.helptext.savepng", + "mw.gui.mwgui.helptext.regenerate", + "mw.gui.mwgui.helptext.undergroundmap" + }; + private final static double PAN_FACTOR = 0.3D; private static final int menuY = 5; @@ -93,7 +129,7 @@ public void draw(int x, int y, String s) { public void drawToRightOf(Label label, String s) { this.draw(label.x + label.w + 5, label.y, s); } - + public boolean posWithin(int x, int y) { return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); @@ -137,17 +173,7 @@ public void initGui() { protected void actionPerformed(GuiButton button) { } - - public void exitGui() { - // MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - + // get a marker near the specified block pos if it exists. // the maxDistance is based on the view width so that you need to click // closer @@ -297,15 +323,9 @@ protected void keyTyped(char c, int key) { this.exitGui(); break; - // case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - default: if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; + this.exitGui(); } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { this.mapView.adjustZoomLevel(-1); } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { @@ -534,110 +554,79 @@ public void mouseDWheelScrolled(int x, int y, int direction) { } } + //closes this gui + public void exitGui() + { + this.mc.displayGuiScreen((GuiScreen)null); + } + + /** + * Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() + { + Keyboard.enableRepeatEvents(false); + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + } + // called every frame public void updateScreen() { - // TODO:MwUtil.log("MwGui.updateScreen() " + - // Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } super.updateScreen(); } - public void drawStatus(int bX, int bY, int bZ) { - String s; + public void drawStatus(int bX, int bY, int bZ) + { + StringBuilder builder = new StringBuilder(); if (bY != 0) { - s = String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ); + builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ)); } else { - s = String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ); + builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ)); } + if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords( - new BlockPos(bX, 0, bZ)).isEmpty()) { - s += String.format(", " + I18n.format("mw.gui.mwgui.status.biome", new Object[0]) + ": %s", - this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, - 0, bZ)).biomeName); + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) + { + builder.append(", " ); + builder.append(I18n.format("mw.gui.mwgui.status.biome", new Object[0])); + builder.append(String.format(": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); } } - /* - * if (this.mw.markerManager.selectedMarker != null) { s += - * ", current marker: " + this.mw.markerManager.selectedMarker.name; } - */ - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, - bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, - 0x80000000); - this.drawCenteredString(this.fontRendererObj, s, this.width / 2, - this.height - 18, 0xffffff); - } - - //TODO: Make this more generic in the label class - //TODO: Make the rectangle not fill whole screen, look at player info hover. - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - - I18n.format("mw.gui.mwgui.helptext.1", new Object[0]) + "\n" + - I18n.format("mw.gui.mwgui.helptext.2", new Object[0]) + "\n" + - I18n.format("mw.gui.mwgui.helptext.3", new Object[0]) + "\n" + - I18n.format("mw.gui.mwgui.helptext.4", new Object[0]) + "\n" + - I18n.format("mw.gui.mwgui.helptext.5", new Object[0]) + "\n" + - I18n.format("mw.gui.mwgui.helptext.6", new Object[0]) + "\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| " + I18n.format("mw.gui.mwgui.helptext.nextmarkergroup", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.deletemarker", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.cyclecolour", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.centermap", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.centermapplayer", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.selectnextmarker", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.teleport", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.savepng", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.regenerate", new Object[0]) + "\n" + - "| " + I18n.format("mw.gui.mwgui.helptext.undergroundmap", new Object[0]) + "\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawUpdate() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString(VersionCheck.getUpdateURL(), 15, - 24, this.width - 30, 0xffffff); + { + builder.append(provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ)); + } + String s = builder.toString(); + int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); + + drawTooltip(new String[]{builder.toString()}, null, x, this.height - 21); } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, - int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max(this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, title, x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, desc, x + 10, y + 4, 0xcccccc); + + //draw a tooltip at x,y containing the strings in the arrays. + //array 2 may be null + public void drawTooltip(String[] s1, String[] s2, int x, int y) + { + int stringwidth = Utils.getMaxWidth(s1, s2); + int w = stringwidth < this.width - 20 ? stringwidth : this.width - 20; + int h = (s1.length) * this.fontRendererObj.FONT_HEIGHT; + + if (x + w + 10 > this.width) + { + x = x - w - 10 - 5; + } + if (y + h + 8 > this.height) + { + y = y - h - 8; + } + + drawRect(x, y, x + w + 10, h + y + 8, 0x80000000); + this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s1), x + 5 , y + 4, w, 0xffffff); + if (s2 != null) + { + this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), x + 65, y + 4, w, 0xffffff); + } } // also called every frame @@ -687,15 +676,41 @@ public void drawScreen(int mouseX, int mouseY, float f) { // draw name of marker under mouse cursor Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, - marker.y, marker.z); + drawTooltip(new String[]{ + marker.name, + String.format("(%d, %d, %d)", + marker.x, + marker.y, + marker.z)}, + null, + mouseX + 5, + mouseY); + } + + // draw name of selected marker + if (this.mw.markerManager.selectedMarker != null) { + drawTooltip(new String[]{ + this.mw.markerManager.selectedMarker.name, + String.format("(%d, %d, %d)", + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.y, + this.mw.markerManager.selectedMarker.z)}, + null, + (int)this.mw.markerManager.selectedMarker.screenPos.x + 5, + (int)this.mw.markerManager.selectedMarker.screenPos.y); } // draw name of player under mouse cursor if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, - this.mc.thePlayer.getDisplayNameString(), - this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); + drawTooltip(new String[]{ + this.mc.thePlayer.getDisplayNameString(), + String.format("(%d, %d, %d)", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt)}, + null, + mouseX + 5, + mouseY); } // draw status message @@ -722,10 +737,10 @@ public void drawScreen(int mouseX, int mouseY, float f) { // help message on mouse over if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); + drawTooltip(HelpText1,HelpText2, 10 , 20); } if (this.updateLabel.posWithin(mouseX, mouseY)) { - this.drawUpdate(); + drawTooltip(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20); } super.drawScreen(mouseX, mouseY, f); From 144829f01094b97098fe08148481f516331da7c3 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:38:56 +0200 Subject: [PATCH 065/109] Refactoring --- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 281 +++--------------- .../java/mapwriter/gui/ScrollableTextBox.java | 234 +++++++++++++++ src/main/java/mapwriter/util/Reference.java | 3 +- src/main/java/mapwriter/util/Utils.java | 34 +++ 4 files changed, 316 insertions(+), 236 deletions(-) create mode 100644 src/main/java/mapwriter/gui/ScrollableTextBox.java diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index d983b3a3..b792c4b4 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -43,195 +43,8 @@ public class MwGuiMarkerDialogNew extends GuiScreen { private int markerY = 80; private int markerZ = 0; private int dimension = 0; - private ResourceLocation leftArrowTexture = new ResourceLocation( - "mapwriter", "textures/map/arrow_text_left.png"); - private ResourceLocation rightArrowTexture = new ResourceLocation( - "mapwriter", "textures/map/arrow_text_right.png"); - - class ScrollableTextBox { - public int x; - public int y; - public int width; - // private int height; - public int labelX; - public int labelY; - public int labelWidth; - public int labelHeight; - public String label; - public boolean drawArrows = false; - public int leftArrowX; - public int rightArrowX; - public int arrowsY; - public int arrowsWidth = 7; - public int arrowsHeight = 12; - public int textFieldX; - public int textFieldY; - public int textFieldWidth; - public int textFieldHeight = 12; - public List scrollableElements; - public GuiTextField textField = null; - - ScrollableTextBox(int x, int y, int width, String label) { - this.x = x; - this.y = y; - this.width = width; - this.label = label; - } - - ScrollableTextBox(int x, int y, int width, String label, - List scrollableElements) { - this.x = x; - this.y = y; - this.width = width; - this.label = label; - this.scrollableElements = scrollableElements; - } - - public void init() { - this.textFieldX = this.x + this.arrowsWidth; - this.textFieldY = this.y; - this.textFieldWidth = this.width - this.arrowsWidth * 2 - 25; - this.labelWidth = MwGuiMarkerDialogNew.this.fontRendererObj - .getStringWidth(this.label); - this.labelHeight = MwGuiMarkerDialogNew.this.fontRendererObj.FONT_HEIGHT; - this.labelX = this.x - this.labelWidth - 4; - this.labelY = this.y + this.labelHeight / 2 - 2; - this.leftArrowX = this.x - 1; - this.rightArrowX = this.textFieldX + this.textFieldWidth + 1; - this.arrowsY = this.y; - this.textField = new GuiTextField(0, - MwGuiMarkerDialogNew.this.fontRendererObj, this.textFieldX, - this.textFieldY, this.textFieldWidth, this.textFieldHeight); - this.textField.setMaxStringLength(32); - } - - public void draw() { - MwGuiMarkerDialogNew screen = MwGuiMarkerDialogNew.this; - screen.drawString(screen.fontRendererObj, this.label, this.labelX, - this.labelY, 0xffffff); - if (this.drawArrows) { - screen.mc.renderEngine.bindTexture(screen.leftArrowTexture); - Render.drawTexturedRect(this.leftArrowX, this.arrowsY, - this.arrowsWidth, this.arrowsHeight, 0.0, 0.0, 1.0, 1.0); - MwGuiMarkerDialogNew.this.mc.renderEngine - .bindTexture(screen.rightArrowTexture); - Render.drawTexturedRect(this.rightArrowX, this.arrowsY, - this.arrowsWidth, this.arrowsHeight, 0.0, 0.0, 1.0, 1.0); - } - this.textField.drawTextBox(); - if (!this.validateTextFieldData()) { - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX + this.textFieldWidth + 1, - this.textFieldY, - 0xff900000); - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX, this.textFieldY + this.textFieldHeight + 1, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + this.textFieldHeight + 1, - this.textFieldX, - this.textFieldY + this.textFieldHeight, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + this.textFieldHeight + 1, - this.textFieldX + this.textFieldWidth, this.textFieldY, - 0xff900000); - } - } - - public void mouseClicked(int x, int y, int button) { - int direction = this.posWithinArrows(x, y); - if (direction != 0) - this.textFieldScroll(direction); - this.textField.mouseClicked(x, y, button); - } - - public void setDrawArrows(boolean value) { - this.drawArrows = value; - } - - public void mouseDWheelScrolled(int x, int y, int direction) { - if (posWithinTextField(x, y)) - textFieldScroll(-direction); - } - - public boolean validateTextFieldData() { - return this.textField.getText().length() > 0; - } - - /** - * - * @return Returns clicked arrow: 1 for right and -1 for left - */ - public int posWithinArrows(int x, int y) { - if ((x >= this.leftArrowX) && (y >= this.arrowsY) - && (x <= this.arrowsWidth + this.leftArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return -1; - else if ((x >= this.rightArrowX) && (y >= this.arrowsY) - && (x <= this.arrowsWidth + this.rightArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return 1; - else - return 0; - } - - public boolean posWithinTextField(int x, int y) { - return (x >= this.textFieldX) && (y >= this.textFieldY) - && (x <= this.textFieldWidth + this.textFieldX) - && (y <= this.textFieldHeight + this.textFieldY); - } - - public void textFieldScroll(int direction) { - if (this.scrollableElements != null) { - int index = this.scrollableElements.indexOf(this.textField - .getText().trim()); - if (direction > 0) { - if (index == -1 - || index == this.scrollableElements.size() - 1) - index = 0; - else - index++; - } else if (direction < 0) { - if (index == -1 || index == 0) - index = this.scrollableElements.size() - 1; - else - index--; - } - this.textField.setText(this.scrollableElements.get(index)); - } - } - } - - class ScrollableNumericTextBox extends ScrollableTextBox { - - public ScrollableNumericTextBox(int x, int y, int width, String label) { - super(x, y, width, label); - } - - @Override - public void textFieldScroll(int direction) { - if (this.validateTextFieldData()) { - int value = this.getTextFieldIntValue(); - if (direction > 0) - this.textField.setText("" + (value + 1)); - else if (direction < 0) - this.textField.setText("" + (value - 1)); - } - } - - public int getTextFieldIntValue() { - return Integer.parseInt(this.textField.getText()); - } - - public void validateTextboxKeyTyped(char c, int key) { - if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK - || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT - || (c == '-' && (this.textField.getCursorPosition() == 0))) - this.textField.textboxKeyTyped(c, key); - } - } + public MwGuiMarkerDialogNew(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { @@ -264,11 +77,11 @@ public MwGuiMarkerDialogNew(GuiScreen parentScreen, public boolean submit() { boolean inputCorrect = true; if (scrollableTextBoxName.validateTextFieldData()) - this.markerName = scrollableTextBoxName.textField.getText(); + this.markerName = scrollableTextBoxName.getText(); else inputCorrect = false; if (scrollableTextBoxGroup.validateTextFieldData()) - this.markerGroup = scrollableTextBoxGroup.textField.getText(); + this.markerGroup = scrollableTextBoxGroup.getText(); else inputCorrect = false; if (scrollableNumericTextBoxX.validateTextFieldData()) @@ -304,31 +117,30 @@ public void initGui() { int width = this.width * dialogWidthPercent / 100 - labelsWidth; int x = (this.width - width) / 2 + labelsWidth; int y = (this.height - elementVSpacing * 5) / 2; - this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, - I18n.format(this.editMarkerName, new Object[0])); - this.scrollableTextBoxName.init(); - this.scrollableTextBoxName.textField.setFocused(true); - this.scrollableTextBoxName.textField.setText(this.markerName); + + this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); + this.scrollableTextBoxName.setFocused(true); + this.scrollableTextBoxName.setText(this.markerName); + this.scrollableTextBoxGroup = new ScrollableTextBox(x, y + this.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), - this.markerManager.groupList); - this.scrollableTextBoxGroup.init(); - this.scrollableTextBoxGroup.textField.setText(this.markerGroup); + this.markerManager.groupList, this.fontRendererObj); + this.scrollableTextBoxGroup.setText(this.markerGroup); this.scrollableTextBoxGroup.setDrawArrows(true); + this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0])); - this.scrollableNumericTextBoxX.init(); - this.scrollableNumericTextBoxX.textField.setText("" + this.markerX); + + this.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxX.setText("" + this.markerX); this.scrollableNumericTextBoxX.setDrawArrows(true); + this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0])); - this.scrollableNumericTextBoxY.init(); - this.scrollableNumericTextBoxY.textField.setText("" + this.markerY); + + this.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxY.setText("" + this.markerY); this.scrollableNumericTextBoxY.setDrawArrows(true); + this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0])); - this.scrollableNumericTextBoxZ.init(); - this.scrollableNumericTextBoxZ.textField.setText("" + this.markerZ); + + this.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxZ.setText("" + this.markerZ); this.scrollableNumericTextBoxZ.setDrawArrows(true); } @@ -364,7 +176,6 @@ public void drawScreen(int mouseX, int mouseY, float f) { // override GuiScreen's handleMouseInput to process // the scroll wheel. - @Override public void handleMouseInput() throws IOException { if (MwAPI.getCurrentDataProvider() != null) @@ -416,35 +227,35 @@ protected void keyTyped(char c, int key) { GuiTextField prevtextField = null; GuiTextField nexttextField = null; - if (this.scrollableTextBoxName.textField.isFocused()) + if (this.scrollableTextBoxName.isFocused()) { - thistextField = scrollableTextBoxName.textField; - prevtextField = scrollableNumericTextBoxZ.textField; - nexttextField = scrollableTextBoxGroup.textField; + thistextField = scrollableTextBoxName; + prevtextField = scrollableNumericTextBoxZ; + nexttextField = scrollableTextBoxGroup; } - else if (this.scrollableTextBoxGroup.textField.isFocused()) + else if (this.scrollableTextBoxGroup.isFocused()) { - thistextField = scrollableTextBoxGroup.textField; - prevtextField = scrollableTextBoxName.textField; - nexttextField = scrollableNumericTextBoxX.textField; + thistextField = scrollableTextBoxGroup; + prevtextField = scrollableTextBoxName; + nexttextField = scrollableNumericTextBoxX; } - else if (this.scrollableNumericTextBoxX.textField.isFocused()) + else if (this.scrollableNumericTextBoxX.isFocused()) { - thistextField = scrollableNumericTextBoxX.textField; - prevtextField = scrollableTextBoxGroup.textField; - nexttextField = scrollableNumericTextBoxY.textField; + thistextField = scrollableNumericTextBoxX; + prevtextField = scrollableTextBoxGroup; + nexttextField = scrollableNumericTextBoxY; } - else if (this.scrollableNumericTextBoxY.textField.isFocused()) + else if (this.scrollableNumericTextBoxY.isFocused()) { - thistextField = scrollableNumericTextBoxY.textField; - prevtextField = scrollableNumericTextBoxX.textField; - nexttextField = scrollableNumericTextBoxZ.textField; + thistextField = scrollableNumericTextBoxY; + prevtextField = scrollableNumericTextBoxX; + nexttextField = scrollableNumericTextBoxZ; } - else if (this.scrollableNumericTextBoxZ.textField.isFocused()) + else if (this.scrollableNumericTextBoxZ.isFocused()) { - thistextField = scrollableNumericTextBoxZ.textField; - prevtextField = scrollableNumericTextBoxY.textField; - nexttextField = scrollableTextBoxName.textField; + thistextField = scrollableNumericTextBoxZ; + prevtextField = scrollableNumericTextBoxY; + nexttextField = scrollableTextBoxName; } thistextField.setFocused(false); @@ -462,15 +273,15 @@ else if (this.scrollableNumericTextBoxZ.textField.isFocused()) break; default: - if (this.scrollableTextBoxName.textField.isFocused()) - this.scrollableTextBoxName.textField.textboxKeyTyped(c, key); - else if (this.scrollableTextBoxGroup.textField.isFocused()) - this.scrollableTextBoxGroup.textField.textboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxX.textField.isFocused()) + if (this.scrollableTextBoxName.isFocused()) + this.scrollableTextBoxName.textboxKeyTyped(c, key); + else if (this.scrollableTextBoxGroup.isFocused()) + this.scrollableTextBoxGroup.textboxKeyTyped(c, key); + else if (this.scrollableNumericTextBoxX.isFocused()) this.scrollableNumericTextBoxX.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxY.textField.isFocused()) + else if (this.scrollableNumericTextBoxY.isFocused()) this.scrollableNumericTextBoxY.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxZ.textField.isFocused()) + else if (this.scrollableNumericTextBoxZ.isFocused()) this.scrollableNumericTextBoxZ.validateTextboxKeyTyped(c, key); break; } diff --git a/src/main/java/mapwriter/gui/ScrollableTextBox.java b/src/main/java/mapwriter/gui/ScrollableTextBox.java new file mode 100644 index 00000000..f5992412 --- /dev/null +++ b/src/main/java/mapwriter/gui/ScrollableTextBox.java @@ -0,0 +1,234 @@ +package mapwriter.gui; + +import java.util.List; + +import org.lwjgl.input.Keyboard; + +import mapwriter.util.Reference; +import mapwriter.util.Render; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.renderer.texture.TextureManager; + +public class ScrollableTextBox extends GuiTextField + { + public int x; + public int y; + public int width; + // private int height; + public int labelX; + public int labelY; + public int labelWidth; + public int labelHeight; + public String label; + public boolean drawArrows = false; + public int leftArrowX; + public int rightArrowX; + public int arrowsY; + public static int arrowsWidth = 7; + public int arrowsHeight = 12; + public int textFieldX; + public int textFieldY; + public int textFieldWidth; + public static int textFieldHeight = 12; + public List scrollableElements; + private final FontRenderer fontRendererInstance; + + ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) + { + super( + 0, + fontrendererObj, + x + arrowsWidth, + y, + width - arrowsWidth * 2 - 25, + textFieldHeight + ); + + this.x = x; + this.y = y; + this.width = width; + this.label = label; + this.fontRendererInstance = fontrendererObj; + + this.init(); + } + + ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) + { + super( + 0, + fontrendererObj, + x + arrowsWidth, + y, + width - arrowsWidth * 2 - 25, + textFieldHeight + ); + + this.x = x; + this.y = y; + this.width = width; + this.label = label; + this.scrollableElements = scrollableElements; + this.fontRendererInstance = fontrendererObj; + this.init(); + } + + private void init() { + setMaxStringLength(32); + this.textFieldX = x + arrowsWidth; + this.textFieldY = this.y; + this.textFieldWidth = width - arrowsWidth * 2 - 25; + this.labelWidth = fontRendererInstance + .getStringWidth(this.label); + this.labelHeight = this.fontRendererInstance.FONT_HEIGHT; + this.labelX = this.x - this.labelWidth - 4; + this.labelY = this.y + this.labelHeight / 2 - 2; + this.leftArrowX = this.x - 1; + this.rightArrowX = this.textFieldX + this.textFieldWidth + 1; + this.arrowsY = this.y; + } + + public void draw() { + drawString(this.fontRendererInstance, this.label, this.labelX, this.labelY, 0xffffff); + if (this.drawArrows) + { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + renderEngine.bindTexture(Reference.leftArrowTexture); + Render.drawTexturedRect( + this.leftArrowX, + this.arrowsY, + this.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + renderEngine.bindTexture(Reference.rightArrowTexture); + Render.drawTexturedRect( + this.rightArrowX, + this.arrowsY, + this.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + } + drawTextBox(); + if (!this.validateTextFieldData()) { + drawRect(this.textFieldX - 1, this.textFieldY - 1, + this.textFieldX + this.textFieldWidth + 1, + this.textFieldY, + 0xff900000); + drawRect(this.textFieldX - 1, this.textFieldY - 1, + this.textFieldX, this.textFieldY + this.textFieldHeight + 1, + 0xff900000); + drawRect(this.textFieldX + this.textFieldWidth + 1, + this.textFieldY + this.textFieldHeight + 1, + this.textFieldX, + this.textFieldY + this.textFieldHeight, + 0xff900000); + drawRect(this.textFieldX + this.textFieldWidth + 1, + this.textFieldY + this.textFieldHeight + 1, + this.textFieldX + this.textFieldWidth, this.textFieldY, + 0xff900000); + } + } + + public void mouseClicked(int x, int y, int button) { + int direction = this.posWithinArrows(x, y); + if (direction != 0) + this.textFieldScroll(direction); + super.mouseClicked(x, y, button); + } + + public void setDrawArrows(boolean value) { + this.drawArrows = value; + } + + public void mouseDWheelScrolled(int x, int y, int direction) { + if (posWithinTextField(x, y)) + textFieldScroll(-direction); + } + + public boolean validateTextFieldData() { + return getText().length() > 0; + } + + /** + * + * @return Returns clicked arrow: 1 for right and -1 for left + */ + public int posWithinArrows(int x, int y) { + if ((x >= this.leftArrowX) && (y >= this.arrowsY) + && (x <= this.arrowsWidth + this.leftArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return -1; + else if ((x >= this.rightArrowX) && (y >= this.arrowsY) + && (x <= this.arrowsWidth + this.rightArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return 1; + else + return 0; + } + + public boolean posWithinTextField(int x, int y) { + return (x >= this.textFieldX) && (y >= this.textFieldY) + && (x <= this.textFieldWidth + this.textFieldX) + && (y <= this.textFieldHeight + this.textFieldY); + } + + public void textFieldScroll(int direction) { + if (this.scrollableElements != null) { + int index = this.scrollableElements.indexOf(getText().trim()); + if (direction > 0) { + if (index == -1 + || index == this.scrollableElements.size() - 1) + index = 0; + else + index++; + } else if (direction < 0) { + if (index == -1 || index == 0) + index = this.scrollableElements.size() - 1; + else + index--; + } + setText(this.scrollableElements.get(index)); + } + } + } + +class ScrollableNumericTextBox extends ScrollableTextBox { + + public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) { + super(x, y, width, label, fontrendererObj); + } + + @Override + public void textFieldScroll(int direction) { + if (this.validateTextFieldData()) { + int value = this.getTextFieldIntValue(); + if (direction > 0) + setText("" + (value + 1)); + else if (direction < 0) + setText("" + (value - 1)); + } + } + + public int getTextFieldIntValue() { + return Integer.parseInt(getText()); + } + + public void validateTextboxKeyTyped(char c, int key) { + if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK + || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT + || (c == '-' && (getCursorPosition() == 0))) + textboxKeyTyped(c, key); + } +} + diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index e123b919..28fe4d9d 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -35,6 +35,7 @@ public final class Reference public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - + public static final ResourceLocation leftArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_left.png"); + public static final ResourceLocation rightArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_right.png"); } diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 439706a4..6bc1c9dd 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -16,6 +16,8 @@ import mapwriter.config.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.resources.I18n; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; @@ -168,6 +170,38 @@ public static void openWebLink(URI p_175282_1_) } } + public static String stringArrayToString(String[] arr) + { + StringBuilder builder = new StringBuilder(); + for(String s : arr) { + builder.append(I18n.format(s, new Object[0])); + builder.append("\n"); + } + return builder.toString(); + } + public static int getMaxWidth(String[] arr, String[] arr2) + { + FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj; + int maxWidth = 1; + for(int i=0; i w2 ? w1 : w2; + maxWidth = maxWidth > wTot ? maxWidth : wTot; + } + return maxWidth; + } + /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * From bd69d1462434637f29628e67373dab8bc9b6b4af Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:58:14 +0200 Subject: [PATCH 066/109] more refactoring --- src/main/java/mapwriter/gui/MwGui.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 19842e11..5c2b9ac3 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -106,8 +106,6 @@ public class MwGui extends GuiScreen { private Label updateLabel; public static MwGui instance; - private static final HashSet PROTOCOLS = Sets.newHashSet(new String[] { "http", - "https" }); private URI clickedLinkURI; class Label { @@ -391,7 +389,7 @@ protected void mouseClicked(int x, int y, int button) { try { uri = new URI(VersionCheck.getUpdateURL()); - if (!PROTOCOLS.contains(uri.getScheme().toLowerCase())) { + if (!Reference.PROTOCOLS.contains(uri.getScheme().toLowerCase())) { throw new URISyntaxException(uri.toString(), "Unsupported protocol: " + uri.getScheme().toLowerCase()); From 2cb67eca3e2c76d252dcc07db4e64ff1fe92a2ca Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 30 Aug 2015 21:58:28 +0200 Subject: [PATCH 067/109] refactoring --- src/main/java/mapwriter/util/Reference.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 28fe4d9d..7f7e9a82 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,7 +1,10 @@ package mapwriter.util; +import java.util.HashSet; import java.util.regex.Pattern; +import com.google.common.collect.Sets; + import net.minecraft.util.ResourceLocation; public final class Reference @@ -38,4 +41,5 @@ public final class Reference public static final ResourceLocation leftArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_left.png"); public static final ResourceLocation rightArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_right.png"); + public static final HashSet PROTOCOLS = Sets.newHashSet(new String[] { "http", "https" }); } From a4fe466e5af01f931d0eb8b0addf95d0a1bdcb01 Mon Sep 17 00:00:00 2001 From: Thijs Date: Mon, 31 Aug 2015 13:00:21 +0200 Subject: [PATCH 068/109] Refactoring Added a overlay on large mad that lists waypoints in the selected group upped version to reflect changes Updated build.gradle to be able to publish to curse --- build.gradle | 11 +- build.properties | 12 +- src/main/java/mapwriter/gui/MwGui.java | 134 +++++++----------- src/main/java/mapwriter/gui/MwGuiLabel.java | 82 +++++++++++ .../mapwriter/gui/MwGuiMarkerListOverlay.java | 68 +++++++++ src/main/java/mapwriter/util/Utils.java | 17 ++- 6 files changed, 228 insertions(+), 96 deletions(-) create mode 100644 src/main/java/mapwriter/gui/MwGuiLabel.java create mode 100644 src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java diff --git a/build.gradle b/build.gradle index 84933804..2943701d 100644 --- a/build.gradle +++ b/build.gradle @@ -16,6 +16,7 @@ buildscript { } apply plugin: 'forge' +apply plugin: 'curseforge' repositories { mavenLocal() @@ -73,7 +74,7 @@ processResources version = "${project.minecraft.version}-${project.version}" jar { -// = 'universal' +//classifier = 'universal' } task sourceJar(type: Jar) { @@ -110,9 +111,15 @@ gradle.taskGraph.whenReady { taskGraph -> if (!taskGraph.allTasks.findAll{ it.name == 'eclipseClasspath' }.empty) { gradle.buildFinished { println '----------------------------------------------------------------------' - print "Please set the Eclipse classpath variable 'GRADLE_CACHE' in Preferences " + print "Please set the Eclipse classpath variable 'GRADLE_USER_HOME' in Preferences " println "-> Java -> Build path -> Classpath Variable to $gradle.gradleUserHomeDir" println '----------------------------------------------------------------------' } } +} + +curse { + projectId = config.curse_project_id + apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : '' + releaseType = 'release' } \ No newline at end of file diff --git a/build.properties b/build.properties index 724d1f9d..f98dd34e 100644 --- a/build.properties +++ b/build.properties @@ -1,6 +1,6 @@ -mod_name=MapWriter -mod_group=vectron -mc_version=1.8 -forge_version=11.14.3.1450 -mcp_version=snapshot_20150615 -mod_version=2.2.7 +mod_name=MapWriter +mod_group=vectron +mc_version=1.8 +forge_version=11.14.3.1450 +mcp_version=snapshot_20150615 +mod_version=2.2.8 diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 5c2b9ac3..4ddcdbfd 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -96,44 +96,24 @@ public class MwGui extends GuiScreen { private int mouseBlockY = 0; private int mouseBlockZ = 0; - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - private Label updateLabel; + private MwGuiLabel helpLabel; + private MwGuiLabel optionsLabel; + private MwGuiLabel dimensionLabel; + private MwGuiLabel groupLabel; + private MwGuiLabel overlayLabel; + private MwGuiLabel updateLabel; + private MwGuiMarkerListOverlay MarkerOverlay; + + private MwGuiLabel helpTooltipLabel; + private MwGuiLabel updateTooltipLabel; + private MwGuiLabel statusLabel; + private MwGuiLabel markerLabel; + public static MwGui instance; + private URI clickedLinkURI; - class Label { - int x = 0, y = 0, w = 1, h = 12; - - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, - 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, - this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) - && (y <= (this.y + this.h)); - } - } - public MwGui(Mw mw) { this.mw = mw; this.mapMode = new FullScreenMapMode(); @@ -145,13 +125,19 @@ public MwGui(Mw mw) { this.mw.playerDimension); this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - this.updateLabel = new Label(); - + this.helpLabel = new MwGuiLabel(this); + this.optionsLabel = new MwGuiLabel(this); + this.dimensionLabel = new MwGuiLabel(this); + this.groupLabel = new MwGuiLabel(this); + this.overlayLabel = new MwGuiLabel(this); + this.updateLabel = new MwGuiLabel(this); + this.helpTooltipLabel = new MwGuiLabel(this); + this.updateTooltipLabel = new MwGuiLabel(this); + this.statusLabel = new MwGuiLabel(this); + this.markerLabel = new MwGuiLabel(this); + + this.MarkerOverlay = new MwGuiMarkerListOverlay(this, this.mw.markerManager); + instance = this; } @@ -599,32 +585,7 @@ public void drawStatus(int bX, int bY, int bZ) String s = builder.toString(); int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); - drawTooltip(new String[]{builder.toString()}, null, x, this.height - 21); - } - - //draw a tooltip at x,y containing the strings in the arrays. - //array 2 may be null - public void drawTooltip(String[] s1, String[] s2, int x, int y) - { - int stringwidth = Utils.getMaxWidth(s1, s2); - int w = stringwidth < this.width - 20 ? stringwidth : this.width - 20; - int h = (s1.length) * this.fontRendererObj.FONT_HEIGHT; - - if (x + w + 10 > this.width) - { - x = x - w - 10 - 5; - } - if (y + h + 8 > this.height) - { - y = y - h - 8; - } - - drawRect(x, y, x + w + 10, h + y + 8, 0x80000000); - this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s1), x + 5 , y + 4, w, 0xffffff); - if (s2 != null) - { - this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), x + 65, y + 4, w, 0xffffff); - } + statusLabel.draw(new String[]{builder.toString()}, null, x, this.height - 21, true, false); } // also called every frame @@ -674,7 +635,7 @@ public void drawScreen(int mouseX, int mouseY, float f) { // draw name of marker under mouse cursor Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); if (marker != null) { - drawTooltip(new String[]{ + markerLabel.draw(new String[]{ marker.name, String.format("(%d, %d, %d)", marker.x, @@ -682,12 +643,15 @@ public void drawScreen(int mouseX, int mouseY, float f) { marker.z)}, null, mouseX + 5, - mouseY); + mouseY, + true, + true + ); } // draw name of selected marker if (this.mw.markerManager.selectedMarker != null) { - drawTooltip(new String[]{ + markerLabel.draw(new String[]{ this.mw.markerManager.selectedMarker.name, String.format("(%d, %d, %d)", this.mw.markerManager.selectedMarker.x, @@ -695,12 +659,15 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.mw.markerManager.selectedMarker.z)}, null, (int)this.mw.markerManager.selectedMarker.screenPos.x + 5, - (int)this.mw.markerManager.selectedMarker.screenPos.y); + (int)this.mw.markerManager.selectedMarker.screenPos.y, + true, + true + ); } // draw name of player under mouse cursor if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - drawTooltip(new String[]{ + markerLabel.draw(new String[]{ this.mc.thePlayer.getDisplayNameString(), String.format("(%d, %d, %d)", this.mw.playerXInt, @@ -708,39 +675,44 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.mw.playerZInt)}, null, mouseX + 5, - mouseY); + mouseY, + true, + true + ); } // draw status message this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); // draw labels - this.helpLabel.draw(menuX, menuY, "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"); + this.helpLabel.draw(new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, null, menuX, menuY, true, false); + this.optionsLabel.drawToRightOf(this.helpLabel, new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, true, false); String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + this.dimensionLabel.drawToRightOf(this.optionsLabel, new String[]{dimString}, true, false); String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + this.groupLabel.drawToRightOf(this.dimensionLabel, new String[]{groupString}, true, false); String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + this.overlayLabel.drawToRightOf(this.groupLabel, new String[]{overlayString}, true, false); if (!VersionCheck.isLatestVersion()) { String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", VersionCheck.getLatestVersion()); - this.updateLabel.drawToRightOf(this.overlayLabel, updateString); + this.updateLabel.drawToRightOf(this.overlayLabel, new String[]{updateString}, true, false); } // help message on mouse over if (this.helpLabel.posWithin(mouseX, mouseY)) { - drawTooltip(HelpText1,HelpText2, 10 , 20); + helpTooltipLabel.draw(HelpText1,HelpText2, 10 , 20, true, false); } if (this.updateLabel.posWithin(mouseX, mouseY)) { - drawTooltip(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20); + updateTooltipLabel.draw(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20, true, false); } + MarkerOverlay.draw(); + super.drawScreen(mouseX, mouseY, f); } diff --git a/src/main/java/mapwriter/gui/MwGuiLabel.java b/src/main/java/mapwriter/gui/MwGuiLabel.java new file mode 100644 index 00000000..9882b5fc --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiLabel.java @@ -0,0 +1,82 @@ +package mapwriter.gui; + +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; + +public class MwGuiLabel +{ + int x = 0, y = 0, w = 1, h = 12; + int spacingX = 10; + int spacingY = 2; + private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; + private final GuiScreen parentScreen; + + public MwGuiLabel(GuiScreen parentScreen) + { + this.parentScreen = parentScreen; + } + + public void draw(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip) { + this.x = x; + this.y = y; + + int stringwidth = Utils.getMaxWidth(s1, s2); + this.w = stringwidth < parentScreen.width - 20 ? stringwidth : parentScreen.width - 20; + + String str = Utils.stringArrayToString(s1); + this.h = fontRendererObj.splitStringWidth(str, parentScreen.width); + + if (AllowFlip) + { + if (this.x + this.w + (spacingX * 2) > parentScreen.width) + { + this.x = this.x - this.w - spacingX - 5; + } + if (this.y + this.h + (spacingY * 2) > parentScreen.height) + { + this.y = this.y - this.h - spacingY; + } + } + + if (this.y + this.h + (spacingY * 2) > parentScreen.height) + { + return; + } + + if(Background) + { + parentScreen.drawRect(this.x, this.y, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); + } + + this.fontRendererObj.drawSplitString(str, this.x + 5 , this.y + 2, this.w, 0xffffff); + + if (s2 != null) + { + this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), this.x + 65, this.y + 2, this.w, 0xffffff); + } + } + + public void drawToRightOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { + this.draw(s, null, label.x + label.w + spacingX + 2, label.y, Background, AllowFlip); + } + + public void drawToLeftOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { + this.draw(s, null, label.x - label.w - spacingX + 2, label.y, Background, AllowFlip); + } + + public void drawToBelowOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { + this.draw(s, null, label.x, label.y + label.h + spacingY + 2, Background, AllowFlip); + } + + public void drawToAboveOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { + this.draw(s, null, label.x, label.y + label.h + spacingY + 2, Background, AllowFlip); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java new file mode 100644 index 00000000..60877e7a --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -0,0 +1,68 @@ +package mapwriter.gui; + +import mapwriter.Mw; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiScreen; + +public class MwGuiMarkerListOverlay extends GuiScreen +{ + private final GuiScreen parentScreen; + private final MarkerManager markerManager; + + //TODO: Make the list scrollable and add button toggle on off + + public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManager) + { + this.parentScreen = parentScreen; + this.markerManager = markerManager; + this.fontRendererObj = Minecraft.getMinecraft().fontRendererObj; + } + + public void draw() + { + int x = parentScreen.width - 110; + int y = 10; + int w = 110 - 5; + int h = parentScreen.height - 20; + Boolean first = true; + MwGuiLabel prevLabel = new MwGuiLabel(this); + + this.width = w; + this.height = h; + + drawRect(x, y, x + w, h + y, 0x80000000); + y += 5; + for (Marker m : markerManager.visibleMarkerList) + { + + MwGuiLabel label = new MwGuiLabel(this); + + String[] text = new String[2]; + text[0] = m.name; + text[1] = String.format( + "(%d, %d, %d)", + m.x, + m.y, + m.z); + if (first) + { + label.draw(text, null, x, y, false, false); + first = false; + } + else + { + label.drawToBelowOf(prevLabel, text, false, false); + } + prevLabel = label; + + if (label.y + label.h + label.h> parentScreen.height) + { + break; + } + } + } +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 6bc1c9dd..97f799c6 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -182,24 +182,27 @@ public static String stringArrayToString(String[] arr) public static int getMaxWidth(String[] arr, String[] arr2) { FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj; - int maxWidth = 1; + int Width = 1; for(int i=0; i w2 ? w1 : w2; - maxWidth = maxWidth > wTot ? maxWidth : wTot; + Width = Width > wTot ? Width : wTot; } - return maxWidth; + return Width; } /* From 3e016218dc734c20a3a628c85b490f40bc1d2719 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 31 Aug 2015 13:36:45 +0200 Subject: [PATCH 069/109] Cleanup on warnings --- src/main/java/mapwriter/gui/MwGui.java | 3 - src/main/java/mapwriter/gui/MwGuiLabel.java | 3 +- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 573 +++++++++--------- .../mapwriter/gui/MwGuiMarkerListOverlay.java | 3 - .../java/mapwriter/gui/ScrollableTextBox.java | 467 +++++++------- src/main/java/mapwriter/region/MwChunk.java | 4 +- src/main/java/mapwriter/util/Utils.java | 4 +- 7 files changed, 522 insertions(+), 535 deletions(-) diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 4ddcdbfd..20c021ad 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.util.HashSet; import mapwriter.Mw; import mapwriter.api.IMwDataProvider; @@ -34,8 +33,6 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import com.google.common.collect.Sets; - @SideOnly(Side.CLIENT) public class MwGui extends GuiScreen { private Mw mw; diff --git a/src/main/java/mapwriter/gui/MwGuiLabel.java b/src/main/java/mapwriter/gui/MwGuiLabel.java index 9882b5fc..ae326e0d 100644 --- a/src/main/java/mapwriter/gui/MwGuiLabel.java +++ b/src/main/java/mapwriter/gui/MwGuiLabel.java @@ -5,7 +5,6 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; public class MwGuiLabel { @@ -49,7 +48,7 @@ public void draw(String[] s1, String[] s2, int x, int y, Boolean Background, Boo if(Background) { - parentScreen.drawRect(this.x, this.y, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); + Gui.drawRect(this.x, this.y, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); } this.fontRendererObj.drawSplitString(str, this.x + 5 , this.y + 2, this.w, 0xffffff); diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index b792c4b4..9c0671da 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -1,289 +1,286 @@ -package mapwriter.gui; - -import java.io.IOException; -import java.util.List; - -import mapwriter.api.MwAPI; -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.util.Render; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.resources.I18n; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.relauncher.Side; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@net.minecraftforge.fml.relauncher.SideOnly(Side.CLIENT) -public class MwGuiMarkerDialogNew extends GuiScreen { - private final GuiScreen parentScreen; - String title = ""; - String titleNew = "mw.gui.mwguimarkerdialognew.title.new"; - String titleEdit = "mw.gui.mwguimarkerdialognew.title.edit"; - private String editMarkerName = "mw.gui.mwguimarkerdialognew.editMarkerName"; - private String editMarkerGroup = "mw.gui.mwguimarkerdialognew.editMarkerGroup"; - private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; - private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; - private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; - ScrollableTextBox scrollableTextBoxName = null; - ScrollableTextBox scrollableTextBoxGroup = null; - ScrollableNumericTextBox scrollableNumericTextBoxX = null; - ScrollableNumericTextBox scrollableNumericTextBoxY = null; - ScrollableNumericTextBox scrollableNumericTextBoxZ = null; - boolean backToGameOnSubmit = false; - static final int dialogWidthPercent = 40; - static final int elementVSpacing = 20; - private final MarkerManager markerManager; - private Marker editingMarker; - private String markerName = ""; - private String markerGroup = ""; - private int markerX = 0; - private int markerY = 80; - private int markerZ = 0; - private int dimension = 0; - - - public MwGuiMarkerDialogNew(GuiScreen parentScreen, - MarkerManager markerManager, String markerName, String markerGroup, - int x, int y, int z, int dimension) { - this.markerManager = markerManager; - this.markerName = markerName; - this.markerGroup = markerGroup; - this.markerX = x; - this.markerY = y; - this.markerZ = z; - this.editingMarker = null; - this.dimension = dimension; - this.parentScreen = parentScreen; - this.title = this.titleNew; - } - - public MwGuiMarkerDialogNew(GuiScreen parentScreen, - MarkerManager markerManager, Marker editingMarker) { - this.markerManager = markerManager; - this.editingMarker = editingMarker; - this.markerName = editingMarker.name; - this.markerGroup = editingMarker.groupName; - this.markerX = editingMarker.x; - this.markerY = editingMarker.y; - this.markerZ = editingMarker.z; - this.dimension = editingMarker.dimension; - this.parentScreen = parentScreen; - this.title = this.titleEdit; - } - - public boolean submit() { - boolean inputCorrect = true; - if (scrollableTextBoxName.validateTextFieldData()) - this.markerName = scrollableTextBoxName.getText(); - else - inputCorrect = false; - if (scrollableTextBoxGroup.validateTextFieldData()) - this.markerGroup = scrollableTextBoxGroup.getText(); - else - inputCorrect = false; - if (scrollableNumericTextBoxX.validateTextFieldData()) - this.markerX = scrollableNumericTextBoxX.getTextFieldIntValue(); - else - inputCorrect = false; - if (scrollableNumericTextBoxY.validateTextFieldData()) - this.markerY = scrollableNumericTextBoxY.getTextFieldIntValue(); - else - inputCorrect = false; - if (scrollableNumericTextBoxZ.validateTextFieldData()) - this.markerZ = scrollableNumericTextBoxZ.getTextFieldIntValue(); - else - inputCorrect = false; - if (inputCorrect) { - int colour = Marker.getCurrentColour(); - if (this.editingMarker != null) { - colour = this.editingMarker.colour; - this.markerManager.delMarker(this.editingMarker); - this.editingMarker = null; - } - this.markerManager.addMarker(this.markerName, this.markerGroup, - this.markerX, this.markerY, this.markerZ, this.dimension, - colour); - this.markerManager.setVisibleGroupName(this.markerGroup); - this.markerManager.update(); - } - return inputCorrect; - } - - public void initGui() { - int labelsWidth = this.fontRendererObj.getStringWidth("Group"); - int width = this.width * dialogWidthPercent / 100 - labelsWidth; - int x = (this.width - width) / 2 + labelsWidth; - int y = (this.height - elementVSpacing * 5) / 2; - - this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); - this.scrollableTextBoxName.setFocused(true); - this.scrollableTextBoxName.setText(this.markerName); - - this.scrollableTextBoxGroup = new ScrollableTextBox(x, y - + this.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), - this.markerManager.groupList, this.fontRendererObj); - this.scrollableTextBoxGroup.setText(this.markerGroup); - this.scrollableTextBoxGroup.setDrawArrows(true); - - this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); - this.scrollableNumericTextBoxX.setText("" + this.markerX); - this.scrollableNumericTextBoxX.setDrawArrows(true); - - this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); - this.scrollableNumericTextBoxY.setText("" + this.markerY); - this.scrollableNumericTextBoxY.setDrawArrows(true); - - this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y - + this.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); - this.scrollableNumericTextBoxZ.setText("" + this.markerZ); - this.scrollableNumericTextBoxZ.setDrawArrows(true); - } - - public void drawScreen(int mouseX, int mouseY, float f) { - if (this.parentScreen != null) { - this.parentScreen.drawScreen(mouseX, mouseY, f); - } else { - this.drawDefaultBackground(); - } - int w = this.width * this.dialogWidthPercent / 100; - int y = (this.height - this.elementVSpacing * 5) / 2 + 2; - drawRect( - (this.width - w) / 2, - (this.height - this.elementVSpacing * 7) / 2 - 4, - (this.width - w) / 2 + w, - (this.height - this.elementVSpacing * 7) / 2 - + this.elementVSpacing * 6, - 0x80000000); - this.drawCenteredString( - this.fontRendererObj, - I18n.format(this.title, new Object[0]), - (this.width) / 2, - (this.height - this.elementVSpacing * 6) / 2 - - this.elementVSpacing / 4, - 0xffffff); - this.scrollableTextBoxName.draw(); - this.scrollableTextBoxGroup.draw(); - this.scrollableNumericTextBoxX.draw(); - this.scrollableNumericTextBoxY.draw(); - this.scrollableNumericTextBoxZ.draw(); - super.drawScreen(mouseX, mouseY, f); - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null) - return; - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height - / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - public void mouseDWheelScrolled(int x, int y, int direction) { - this.scrollableTextBoxName.mouseDWheelScrolled(x, y, direction); - this.scrollableTextBoxGroup.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxX.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxY.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxZ.mouseDWheelScrolled(x, y, direction); - } - - protected void mouseClicked(int x, int y, int button) throws IOException { - super.mouseClicked(x, y, button); - this.scrollableTextBoxName.mouseClicked(x, y, button); - this.scrollableTextBoxGroup.mouseClicked(x, y, button); - this.scrollableNumericTextBoxX.mouseClicked(x, y, button); - this.scrollableNumericTextBoxY.mouseClicked(x, y, button); - this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); - } - - protected void keyTyped(char c, int key) { - switch (key) { - case Keyboard.KEY_ESCAPE: - this.mc.displayGuiScreen(this.parentScreen); - break; - case Keyboard.KEY_RETURN: - // when enter pressed, submit current input - if (this.submit()) { - if (!this.backToGameOnSubmit) { - this.mc.displayGuiScreen(this.parentScreen); - } else { - this.mc.displayGuiScreen(null); - } - } - break; - case Keyboard.KEY_TAB: - GuiTextField thistextField = null; - GuiTextField prevtextField = null; - GuiTextField nexttextField = null; - - if (this.scrollableTextBoxName.isFocused()) - { - thistextField = scrollableTextBoxName; - prevtextField = scrollableNumericTextBoxZ; - nexttextField = scrollableTextBoxGroup; - } - else if (this.scrollableTextBoxGroup.isFocused()) - { - thistextField = scrollableTextBoxGroup; - prevtextField = scrollableTextBoxName; - nexttextField = scrollableNumericTextBoxX; - } - else if (this.scrollableNumericTextBoxX.isFocused()) - { - thistextField = scrollableNumericTextBoxX; - prevtextField = scrollableTextBoxGroup; - nexttextField = scrollableNumericTextBoxY; - } - else if (this.scrollableNumericTextBoxY.isFocused()) - { - thistextField = scrollableNumericTextBoxY; - prevtextField = scrollableNumericTextBoxX; - nexttextField = scrollableNumericTextBoxZ; - } - else if (this.scrollableNumericTextBoxZ.isFocused()) - { - thistextField = scrollableNumericTextBoxZ; - prevtextField = scrollableNumericTextBoxY; - nexttextField = scrollableTextBoxName; - } - - thistextField.setFocused(false); - thistextField.setCursorPositionEnd(); - if (Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)) - { - prevtextField.setFocused(true); - prevtextField.setSelectionPos(0); - } - else - { - nexttextField.setFocused(true); - nexttextField.setSelectionPos(0); - } - - break; - default: - if (this.scrollableTextBoxName.isFocused()) - this.scrollableTextBoxName.textboxKeyTyped(c, key); - else if (this.scrollableTextBoxGroup.isFocused()) - this.scrollableTextBoxGroup.textboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxX.isFocused()) - this.scrollableNumericTextBoxX.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxY.isFocused()) - this.scrollableNumericTextBoxY.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxZ.isFocused()) - this.scrollableNumericTextBoxZ.validateTextboxKeyTyped(c, key); - break; - } - } +package mapwriter.gui; + +import java.io.IOException; + +import mapwriter.api.MwAPI; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.relauncher.Side; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +@net.minecraftforge.fml.relauncher.SideOnly(Side.CLIENT) +public class MwGuiMarkerDialogNew extends GuiScreen { + private final GuiScreen parentScreen; + String title = ""; + String titleNew = "mw.gui.mwguimarkerdialognew.title.new"; + String titleEdit = "mw.gui.mwguimarkerdialognew.title.edit"; + private String editMarkerName = "mw.gui.mwguimarkerdialognew.editMarkerName"; + private String editMarkerGroup = "mw.gui.mwguimarkerdialognew.editMarkerGroup"; + private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; + private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; + private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; + ScrollableTextBox scrollableTextBoxName = null; + ScrollableTextBox scrollableTextBoxGroup = null; + ScrollableNumericTextBox scrollableNumericTextBoxX = null; + ScrollableNumericTextBox scrollableNumericTextBoxY = null; + ScrollableNumericTextBox scrollableNumericTextBoxZ = null; + boolean backToGameOnSubmit = false; + static final int dialogWidthPercent = 40; + static final int elementVSpacing = 20; + private final MarkerManager markerManager; + private Marker editingMarker; + private String markerName = ""; + private String markerGroup = ""; + private int markerX = 0; + private int markerY = 80; + private int markerZ = 0; + private int dimension = 0; + + + public MwGuiMarkerDialogNew(GuiScreen parentScreen, + MarkerManager markerManager, String markerName, String markerGroup, + int x, int y, int z, int dimension) { + this.markerManager = markerManager; + this.markerName = markerName; + this.markerGroup = markerGroup; + this.markerX = x; + this.markerY = y; + this.markerZ = z; + this.editingMarker = null; + this.dimension = dimension; + this.parentScreen = parentScreen; + this.title = this.titleNew; + } + + public MwGuiMarkerDialogNew(GuiScreen parentScreen, + MarkerManager markerManager, Marker editingMarker) { + this.markerManager = markerManager; + this.editingMarker = editingMarker; + this.markerName = editingMarker.name; + this.markerGroup = editingMarker.groupName; + this.markerX = editingMarker.x; + this.markerY = editingMarker.y; + this.markerZ = editingMarker.z; + this.dimension = editingMarker.dimension; + this.parentScreen = parentScreen; + this.title = this.titleEdit; + } + + public boolean submit() { + boolean inputCorrect = true; + if (scrollableTextBoxName.validateTextFieldData()) + this.markerName = scrollableTextBoxName.getText(); + else + inputCorrect = false; + if (scrollableTextBoxGroup.validateTextFieldData()) + this.markerGroup = scrollableTextBoxGroup.getText(); + else + inputCorrect = false; + if (scrollableNumericTextBoxX.validateTextFieldData()) + this.markerX = scrollableNumericTextBoxX.getTextFieldIntValue(); + else + inputCorrect = false; + if (scrollableNumericTextBoxY.validateTextFieldData()) + this.markerY = scrollableNumericTextBoxY.getTextFieldIntValue(); + else + inputCorrect = false; + if (scrollableNumericTextBoxZ.validateTextFieldData()) + this.markerZ = scrollableNumericTextBoxZ.getTextFieldIntValue(); + else + inputCorrect = false; + if (inputCorrect) { + int colour = Marker.getCurrentColour(); + if (this.editingMarker != null) { + colour = this.editingMarker.colour; + this.markerManager.delMarker(this.editingMarker); + this.editingMarker = null; + } + this.markerManager.addMarker(this.markerName, this.markerGroup, + this.markerX, this.markerY, this.markerZ, this.dimension, + colour); + this.markerManager.setVisibleGroupName(this.markerGroup); + this.markerManager.update(); + } + return inputCorrect; + } + + public void initGui() { + int labelsWidth = this.fontRendererObj.getStringWidth("Group"); + int width = this.width * dialogWidthPercent / 100 - labelsWidth; + int x = (this.width - width) / 2 + labelsWidth; + int y = (this.height - elementVSpacing * 5) / 2; + + this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); + this.scrollableTextBoxName.setFocused(true); + this.scrollableTextBoxName.setText(this.markerName); + + this.scrollableTextBoxGroup = new ScrollableTextBox(x, y + + MwGuiMarkerDialogNew.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), + this.markerManager.groupList, this.fontRendererObj); + this.scrollableTextBoxGroup.setText(this.markerGroup); + this.scrollableTextBoxGroup.setDrawArrows(true); + + this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y + + MwGuiMarkerDialogNew.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxX.setText("" + this.markerX); + this.scrollableNumericTextBoxX.setDrawArrows(true); + + this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y + + MwGuiMarkerDialogNew.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxY.setText("" + this.markerY); + this.scrollableNumericTextBoxY.setDrawArrows(true); + + this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y + + MwGuiMarkerDialogNew.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxZ.setText("" + this.markerZ); + this.scrollableNumericTextBoxZ.setDrawArrows(true); + } + + public void drawScreen(int mouseX, int mouseY, float f) { + if (this.parentScreen != null) { + this.parentScreen.drawScreen(mouseX, mouseY, f); + } else { + this.drawDefaultBackground(); + } + int w = this.width * MwGuiMarkerDialogNew.dialogWidthPercent / 100; + //int y = (this.height - MwGuiMarkerDialogNew.elementVSpacing * 5) / 2 + 2; + drawRect( + (this.width - w) / 2, + (this.height - MwGuiMarkerDialogNew.elementVSpacing * 7) / 2 - 4, + (this.width - w) / 2 + w, + (this.height - MwGuiMarkerDialogNew.elementVSpacing * 7) / 2 + + MwGuiMarkerDialogNew.elementVSpacing * 6, + 0x80000000); + this.drawCenteredString( + this.fontRendererObj, + I18n.format(this.title, new Object[0]), + (this.width) / 2, + (this.height - MwGuiMarkerDialogNew.elementVSpacing * 6) / 2 + - MwGuiMarkerDialogNew.elementVSpacing / 4, + 0xffffff); + this.scrollableTextBoxName.draw(); + this.scrollableTextBoxGroup.draw(); + this.scrollableNumericTextBoxX.draw(); + this.scrollableNumericTextBoxY.draw(); + this.scrollableNumericTextBoxZ.draw(); + super.drawScreen(mouseX, mouseY, f); + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (MwAPI.getCurrentDataProvider() != null) + return; + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height + / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + public void mouseDWheelScrolled(int x, int y, int direction) { + this.scrollableTextBoxName.mouseDWheelScrolled(x, y, direction); + this.scrollableTextBoxGroup.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxX.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxY.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxZ.mouseDWheelScrolled(x, y, direction); + } + + protected void mouseClicked(int x, int y, int button) throws IOException { + super.mouseClicked(x, y, button); + this.scrollableTextBoxName.mouseClicked(x, y, button); + this.scrollableTextBoxGroup.mouseClicked(x, y, button); + this.scrollableNumericTextBoxX.mouseClicked(x, y, button); + this.scrollableNumericTextBoxY.mouseClicked(x, y, button); + this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); + } + + protected void keyTyped(char c, int key) { + switch (key) { + case Keyboard.KEY_ESCAPE: + this.mc.displayGuiScreen(this.parentScreen); + break; + case Keyboard.KEY_RETURN: + // when enter pressed, submit current input + if (this.submit()) { + if (!this.backToGameOnSubmit) { + this.mc.displayGuiScreen(this.parentScreen); + } else { + this.mc.displayGuiScreen(null); + } + } + break; + case Keyboard.KEY_TAB: + GuiTextField thistextField = null; + GuiTextField prevtextField = null; + GuiTextField nexttextField = null; + + if (this.scrollableTextBoxName.isFocused()) + { + thistextField = scrollableTextBoxName; + prevtextField = scrollableNumericTextBoxZ; + nexttextField = scrollableTextBoxGroup; + } + else if (this.scrollableTextBoxGroup.isFocused()) + { + thistextField = scrollableTextBoxGroup; + prevtextField = scrollableTextBoxName; + nexttextField = scrollableNumericTextBoxX; + } + else if (this.scrollableNumericTextBoxX.isFocused()) + { + thistextField = scrollableNumericTextBoxX; + prevtextField = scrollableTextBoxGroup; + nexttextField = scrollableNumericTextBoxY; + } + else if (this.scrollableNumericTextBoxY.isFocused()) + { + thistextField = scrollableNumericTextBoxY; + prevtextField = scrollableNumericTextBoxX; + nexttextField = scrollableNumericTextBoxZ; + } + else if (this.scrollableNumericTextBoxZ.isFocused()) + { + thistextField = scrollableNumericTextBoxZ; + prevtextField = scrollableNumericTextBoxY; + nexttextField = scrollableTextBoxName; + } + + thistextField.setFocused(false); + thistextField.setCursorPositionEnd(); + if (Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)) + { + prevtextField.setFocused(true); + prevtextField.setSelectionPos(0); + } + else + { + nexttextField.setFocused(true); + nexttextField.setSelectionPos(0); + } + + break; + default: + if (this.scrollableTextBoxName.isFocused()) + this.scrollableTextBoxName.textboxKeyTyped(c, key); + else if (this.scrollableTextBoxGroup.isFocused()) + this.scrollableTextBoxGroup.textboxKeyTyped(c, key); + else if (this.scrollableNumericTextBoxX.isFocused()) + this.scrollableNumericTextBoxX.validateTextboxKeyTyped(c, key); + else if (this.scrollableNumericTextBoxY.isFocused()) + this.scrollableNumericTextBoxY.validateTextboxKeyTyped(c, key); + else if (this.scrollableNumericTextBoxZ.isFocused()) + this.scrollableNumericTextBoxZ.validateTextboxKeyTyped(c, key); + break; + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java index 60877e7a..4ba1b98d 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -1,11 +1,8 @@ package mapwriter.gui; -import mapwriter.Mw; -import mapwriter.map.MapView; import mapwriter.map.Marker; import mapwriter.map.MarkerManager; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; public class MwGuiMarkerListOverlay extends GuiScreen diff --git a/src/main/java/mapwriter/gui/ScrollableTextBox.java b/src/main/java/mapwriter/gui/ScrollableTextBox.java index f5992412..4f28b1eb 100644 --- a/src/main/java/mapwriter/gui/ScrollableTextBox.java +++ b/src/main/java/mapwriter/gui/ScrollableTextBox.java @@ -1,234 +1,233 @@ -package mapwriter.gui; - -import java.util.List; - -import org.lwjgl.input.Keyboard; - -import mapwriter.util.Reference; -import mapwriter.util.Render; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.renderer.texture.TextureManager; - -public class ScrollableTextBox extends GuiTextField - { - public int x; - public int y; - public int width; - // private int height; - public int labelX; - public int labelY; - public int labelWidth; - public int labelHeight; - public String label; - public boolean drawArrows = false; - public int leftArrowX; - public int rightArrowX; - public int arrowsY; - public static int arrowsWidth = 7; - public int arrowsHeight = 12; - public int textFieldX; - public int textFieldY; - public int textFieldWidth; - public static int textFieldHeight = 12; - public List scrollableElements; - private final FontRenderer fontRendererInstance; - - ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) - { - super( - 0, - fontrendererObj, - x + arrowsWidth, - y, - width - arrowsWidth * 2 - 25, - textFieldHeight - ); - - this.x = x; - this.y = y; - this.width = width; - this.label = label; - this.fontRendererInstance = fontrendererObj; - - this.init(); - } - - ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) - { - super( - 0, - fontrendererObj, - x + arrowsWidth, - y, - width - arrowsWidth * 2 - 25, - textFieldHeight - ); - - this.x = x; - this.y = y; - this.width = width; - this.label = label; - this.scrollableElements = scrollableElements; - this.fontRendererInstance = fontrendererObj; - this.init(); - } - - private void init() { - setMaxStringLength(32); - this.textFieldX = x + arrowsWidth; - this.textFieldY = this.y; - this.textFieldWidth = width - arrowsWidth * 2 - 25; - this.labelWidth = fontRendererInstance - .getStringWidth(this.label); - this.labelHeight = this.fontRendererInstance.FONT_HEIGHT; - this.labelX = this.x - this.labelWidth - 4; - this.labelY = this.y + this.labelHeight / 2 - 2; - this.leftArrowX = this.x - 1; - this.rightArrowX = this.textFieldX + this.textFieldWidth + 1; - this.arrowsY = this.y; - } - - public void draw() { - drawString(this.fontRendererInstance, this.label, this.labelX, this.labelY, 0xffffff); - if (this.drawArrows) - { - TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; - renderEngine.bindTexture(Reference.leftArrowTexture); - Render.drawTexturedRect( - this.leftArrowX, - this.arrowsY, - this.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); - renderEngine.bindTexture(Reference.rightArrowTexture); - Render.drawTexturedRect( - this.rightArrowX, - this.arrowsY, - this.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); - } - drawTextBox(); - if (!this.validateTextFieldData()) { - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX + this.textFieldWidth + 1, - this.textFieldY, - 0xff900000); - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX, this.textFieldY + this.textFieldHeight + 1, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + this.textFieldHeight + 1, - this.textFieldX, - this.textFieldY + this.textFieldHeight, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + this.textFieldHeight + 1, - this.textFieldX + this.textFieldWidth, this.textFieldY, - 0xff900000); - } - } - - public void mouseClicked(int x, int y, int button) { - int direction = this.posWithinArrows(x, y); - if (direction != 0) - this.textFieldScroll(direction); - super.mouseClicked(x, y, button); - } - - public void setDrawArrows(boolean value) { - this.drawArrows = value; - } - - public void mouseDWheelScrolled(int x, int y, int direction) { - if (posWithinTextField(x, y)) - textFieldScroll(-direction); - } - - public boolean validateTextFieldData() { - return getText().length() > 0; - } - - /** - * - * @return Returns clicked arrow: 1 for right and -1 for left - */ - public int posWithinArrows(int x, int y) { - if ((x >= this.leftArrowX) && (y >= this.arrowsY) - && (x <= this.arrowsWidth + this.leftArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return -1; - else if ((x >= this.rightArrowX) && (y >= this.arrowsY) - && (x <= this.arrowsWidth + this.rightArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return 1; - else - return 0; - } - - public boolean posWithinTextField(int x, int y) { - return (x >= this.textFieldX) && (y >= this.textFieldY) - && (x <= this.textFieldWidth + this.textFieldX) - && (y <= this.textFieldHeight + this.textFieldY); - } - - public void textFieldScroll(int direction) { - if (this.scrollableElements != null) { - int index = this.scrollableElements.indexOf(getText().trim()); - if (direction > 0) { - if (index == -1 - || index == this.scrollableElements.size() - 1) - index = 0; - else - index++; - } else if (direction < 0) { - if (index == -1 || index == 0) - index = this.scrollableElements.size() - 1; - else - index--; - } - setText(this.scrollableElements.get(index)); - } - } - } - -class ScrollableNumericTextBox extends ScrollableTextBox { - - public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) { - super(x, y, width, label, fontrendererObj); - } - - @Override - public void textFieldScroll(int direction) { - if (this.validateTextFieldData()) { - int value = this.getTextFieldIntValue(); - if (direction > 0) - setText("" + (value + 1)); - else if (direction < 0) - setText("" + (value - 1)); - } - } - - public int getTextFieldIntValue() { - return Integer.parseInt(getText()); - } - - public void validateTextboxKeyTyped(char c, int key) { - if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK - || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT - || (c == '-' && (getCursorPosition() == 0))) - textboxKeyTyped(c, key); - } -} - +package mapwriter.gui; + +import java.util.List; + +import mapwriter.util.Reference; +import mapwriter.util.Render; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.renderer.texture.TextureManager; + +import org.lwjgl.input.Keyboard; + +public class ScrollableTextBox extends GuiTextField + { + public int x; + public int y; + public int width; + // private int height; + public int labelX; + public int labelY; + public int labelWidth; + public int labelHeight; + public String label; + public boolean drawArrows = false; + public int leftArrowX; + public int rightArrowX; + public int arrowsY; + public static int arrowsWidth = 7; + public int arrowsHeight = 12; + public int textFieldX; + public int textFieldY; + public int textFieldWidth; + public static int textFieldHeight = 12; + public List scrollableElements; + private final FontRenderer fontRendererInstance; + + ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) + { + super( + 0, + fontrendererObj, + x + arrowsWidth, + y, + width - arrowsWidth * 2 - 25, + textFieldHeight + ); + + this.x = x; + this.y = y; + this.width = width; + this.label = label; + this.fontRendererInstance = fontrendererObj; + + this.init(); + } + + ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) + { + super( + 0, + fontrendererObj, + x + arrowsWidth, + y, + width - arrowsWidth * 2 - 25, + textFieldHeight + ); + + this.x = x; + this.y = y; + this.width = width; + this.label = label; + this.scrollableElements = scrollableElements; + this.fontRendererInstance = fontrendererObj; + this.init(); + } + + private void init() { + setMaxStringLength(32); + this.textFieldX = x + arrowsWidth; + this.textFieldY = this.y; + this.textFieldWidth = width - arrowsWidth * 2 - 25; + this.labelWidth = fontRendererInstance + .getStringWidth(this.label); + this.labelHeight = this.fontRendererInstance.FONT_HEIGHT; + this.labelX = this.x - this.labelWidth - 4; + this.labelY = this.y + this.labelHeight / 2 - 2; + this.leftArrowX = this.x - 1; + this.rightArrowX = this.textFieldX + this.textFieldWidth + 1; + this.arrowsY = this.y; + } + + public void draw() { + drawString(this.fontRendererInstance, this.label, this.labelX, this.labelY, 0xffffff); + if (this.drawArrows) + { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + renderEngine.bindTexture(Reference.leftArrowTexture); + Render.drawTexturedRect( + this.leftArrowX, + this.arrowsY, + ScrollableTextBox.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + renderEngine.bindTexture(Reference.rightArrowTexture); + Render.drawTexturedRect( + this.rightArrowX, + this.arrowsY, + ScrollableTextBox.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + } + drawTextBox(); + if (!this.validateTextFieldData()) { + drawRect(this.textFieldX - 1, this.textFieldY - 1, + this.textFieldX + this.textFieldWidth + 1, + this.textFieldY, + 0xff900000); + drawRect(this.textFieldX - 1, this.textFieldY - 1, + this.textFieldX, this.textFieldY + ScrollableTextBox.textFieldHeight + 1, + 0xff900000); + drawRect(this.textFieldX + this.textFieldWidth + 1, + this.textFieldY + ScrollableTextBox.textFieldHeight + 1, + this.textFieldX, + this.textFieldY + ScrollableTextBox.textFieldHeight, + 0xff900000); + drawRect(this.textFieldX + this.textFieldWidth + 1, + this.textFieldY + ScrollableTextBox.textFieldHeight + 1, + this.textFieldX + this.textFieldWidth, this.textFieldY, + 0xff900000); + } + } + + public void mouseClicked(int x, int y, int button) { + int direction = this.posWithinArrows(x, y); + if (direction != 0) + this.textFieldScroll(direction); + super.mouseClicked(x, y, button); + } + + public void setDrawArrows(boolean value) { + this.drawArrows = value; + } + + public void mouseDWheelScrolled(int x, int y, int direction) { + if (posWithinTextField(x, y)) + textFieldScroll(-direction); + } + + public boolean validateTextFieldData() { + return getText().length() > 0; + } + + /** + * + * @return Returns clicked arrow: 1 for right and -1 for left + */ + public int posWithinArrows(int x, int y) { + if ((x >= this.leftArrowX) && (y >= this.arrowsY) + && (x <= ScrollableTextBox.arrowsWidth + this.leftArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return -1; + else if ((x >= this.rightArrowX) && (y >= this.arrowsY) + && (x <= ScrollableTextBox.arrowsWidth + this.rightArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return 1; + else + return 0; + } + + public boolean posWithinTextField(int x, int y) { + return (x >= this.textFieldX) && (y >= this.textFieldY) + && (x <= this.textFieldWidth + this.textFieldX) + && (y <= ScrollableTextBox.textFieldHeight + this.textFieldY); + } + + public void textFieldScroll(int direction) { + if (this.scrollableElements != null) { + int index = this.scrollableElements.indexOf(getText().trim()); + if (direction > 0) { + if (index == -1 + || index == this.scrollableElements.size() - 1) + index = 0; + else + index++; + } else if (direction < 0) { + if (index == -1 || index == 0) + index = this.scrollableElements.size() - 1; + else + index--; + } + setText(this.scrollableElements.get(index)); + } + } + } + +class ScrollableNumericTextBox extends ScrollableTextBox { + + public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) { + super(x, y, width, label, fontrendererObj); + } + + @Override + public void textFieldScroll(int direction) { + if (this.validateTextFieldData()) { + int value = this.getTextFieldIntValue(); + if (direction > 0) + setText("" + (value + 1)); + else if (direction < 0) + setText("" + (value - 1)); + } + } + + public int getTextFieldIntValue() { + return Integer.parseInt(getText()); + } + + public void validateTextboxKeyTyped(char c, int key) { + if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK + || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT + || (c == '-' && (getCursorPosition() == 0))) + textboxKeyTyped(c, key); + } +} + diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 259581ed..e8a6ebef 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -22,8 +22,6 @@ import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Level; - public class MwChunk implements IChunk { public static final int SIZE = 16; @@ -301,7 +299,7 @@ public int getBlockAndMetadata(int x, int y, int z) { } if (FMPMethodParts != null) { try { - for (Object temp : (List) FMPMethodParts.invoke(value)) { + for (Object temp : (List) FMPMethodParts.invoke(value)) { Object material = FMPMethodMaterial.invoke(temp); Block block = (Block) FMPFieldBlock.get(material); id = Block.getIdFromBlock(block); diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 97f799c6..734a97f5 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -185,8 +185,8 @@ public static int getMaxWidth(String[] arr, String[] arr2) int Width = 1; for(int i=0; i Date: Sun, 6 Sep 2015 20:54:07 +0200 Subject: [PATCH 070/109] added a toggable marker list on the fullscreen map. it shows all markers in the active group on the map --- src/main/java/mapwriter/gui/MwGui.java | 1472 +++++++++-------- src/main/java/mapwriter/gui/MwGuiLabel.java | 155 +- .../mapwriter/gui/MwGuiMarkerListOverlay.java | 180 +- src/main/java/mapwriter/gui/MwGuiSlot.java | 554 +++++++ .../assets/mapwriter/lang/en_US.lang | 298 ++-- 5 files changed, 1640 insertions(+), 1019 deletions(-) create mode 100644 src/main/java/mapwriter/gui/MwGuiSlot.java diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 20c021ad..5c70e788 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -1,726 +1,746 @@ -package mapwriter.gui; - -import java.awt.Point; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import mapwriter.Mw; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.config.Config; -import mapwriter.config.WorldConfig; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import mapwriter.util.Logging; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import mapwriter.util.VersionCheck; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraft.util.BlockPos; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - public MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private String[] HelpText1 = new String[]{ - "Keys:", - "", - " Space", - " Delete", - " C", - " Home", - " End", - " N", - " T", - " P", - " R", - " U", - "", - "mw.gui.mwgui.helptext.1", - "mw.gui.mwgui.helptext.2", - "mw.gui.mwgui.helptext.3", - "mw.gui.mwgui.helptext.4", - "mw.gui.mwgui.helptext.5", - "mw.gui.mwgui.helptext.6" - }; - private String[] HelpText2 = new String[]{ - "", - "", - "mw.gui.mwgui.helptext.nextmarkergroup", - "mw.gui.mwgui.helptext.deletemarker", - "mw.gui.mwgui.helptext.cyclecolour", - "mw.gui.mwgui.helptext.centermap", - "mw.gui.mwgui.helptext.centermapplayer", - "mw.gui.mwgui.helptext.selectnextmarker", - "mw.gui.mwgui.helptext.teleport", - "mw.gui.mwgui.helptext.savepng", - "mw.gui.mwgui.helptext.regenerate", - "mw.gui.mwgui.helptext.undergroundmap" - }; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private MwGuiLabel helpLabel; - private MwGuiLabel optionsLabel; - private MwGuiLabel dimensionLabel; - private MwGuiLabel groupLabel; - private MwGuiLabel overlayLabel; - private MwGuiLabel updateLabel; - private MwGuiMarkerListOverlay MarkerOverlay; - - private MwGuiLabel helpTooltipLabel; - private MwGuiLabel updateTooltipLabel; - private MwGuiLabel statusLabel; - private MwGuiLabel markerLabel; - - public static MwGui instance; - - - private URI clickedLinkURI; - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(); - this.mapView = new MapView(this.mw, true); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - - this.helpLabel = new MwGuiLabel(this); - this.optionsLabel = new MwGuiLabel(this); - this.dimensionLabel = new MwGuiLabel(this); - this.groupLabel = new MwGuiLabel(this); - this.overlayLabel = new MwGuiLabel(this); - this.updateLabel = new MwGuiLabel(this); - this.helpTooltipLabel = new MwGuiLabel(this); - this.updateTooltipLabel = new MwGuiLabel(this); - this.statusLabel = new MwGuiLabel(this); - this.markerLabel = new MwGuiLabel(this); - - this.MarkerOverlay = new MwGuiMarkerListOverlay(this, this.mw.markerManager); - - instance = this; - } - - public MwGui(Mw mw, int dim, int x, int z) { - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click - // closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) - && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - // MwUtil.log("deleting marker %s", - // this.mw.markerManager.selectedMarker.name); - this.mw.markerManager - .delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir - .getName())); - - Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() - + "'"); - } - - public void regenerateView() { - Utils.printBoth(String.format( - I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + - " %dx%d " + - I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + - " (%d, %d)", - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); - // this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch (key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, 0); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, - this.mapView, this.mouseBlockX, - Config.defaultTeleportHeight, this.mouseBlockZ)); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - this.exitGui(); - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(Config.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null - && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, - this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height - / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) { - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, - this.mw, this.mapView, this.mapView.getDimension())); - } else if (this.optionsLabel.posWithin(x, y)) { - try { - GuiScreen newScreen = ModGuiConfig.class.getConstructor( - GuiScreen.class).newInstance(this); - this.mc.displayGuiScreen(newScreen); - } catch (Exception e) { - Logging.logError( - "There was a critical issue trying to build the config GUI for %s", - Reference.MOD_ID); - } - - // this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else if (this.updateLabel.posWithin(x, y)) { - URI uri; - - if (!this.mc.gameSettings.chatLinks) { - return; - } - - try { - uri = new URI(VersionCheck.getUpdateURL()); - - if (!Reference.PROTOCOLS.contains(uri.getScheme().toLowerCase())) { - throw new URISyntaxException(uri.toString(), - "Unsupported protocol: " - + uri.getScheme().toLowerCase()); - } - - if (this.mc.gameSettings.chatLinksPrompt) { - this.clickedLinkURI = uri; - this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, - uri.toString(), 31102009, false)); - } else { - Utils.openWebLink(uri); - } - } catch (URISyntaxException urisyntaxexception) { - Logging.logError("Can\'t open url for %s", - urisyntaxexception); - } - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - // this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - if (Config.newMarkerDialog) - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialogNew(this, - this.mw.markerManager, marker - ) - ); - } - else - { - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, marker)); - } - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = I18n.format("mw.gui.mwgui.group", new Object[0]); - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY - : Config.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - if (Config.newMarkerDialog) - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialogNew( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - else - { - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, "", group, mx, my, mz, - this.mapView.getDimension())); - } - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, - y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), - blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - // this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { - // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - // this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) - && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, - n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated( - this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, - this.mouseBlockX, this.mouseBlockZ); - Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); - } - } - - //closes this gui - public void exitGui() - { - this.mc.displayGuiScreen((GuiScreen)null); - } - - /** - * Called when the screen is unloaded. Used to disable keyboard repeat events - */ - public void onGuiClosed() - { - Keyboard.enableRepeatEvents(false); - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - Keyboard.enableRepeatEvents(false); - } - - // called every frame - public void updateScreen() { - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) - { - StringBuilder builder = new StringBuilder(); - if (bY != 0) { - builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ)); - } else { - builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ)); - } - - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) - { - builder.append(", " ); - builder.append(I18n.format("mw.gui.mwgui.status.biome", new Object[0])); - builder.append(String.format(": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); - } - } - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - { - builder.append(provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ)); - } - String s = builder.toString(); - int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); - - statusLabel.draw(new String[]{builder.toString()}, null, x, this.height - 21, true, false); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - // double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) - * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) - * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView - .getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, - this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - // this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, - this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - markerLabel.draw(new String[]{ - marker.name, - String.format("(%d, %d, %d)", - marker.x, - marker.y, - marker.z)}, - null, - mouseX + 5, - mouseY, - true, - true - ); - } - - // draw name of selected marker - if (this.mw.markerManager.selectedMarker != null) { - markerLabel.draw(new String[]{ - this.mw.markerManager.selectedMarker.name, - String.format("(%d, %d, %d)", - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.y, - this.mw.markerManager.selectedMarker.z)}, - null, - (int)this.mw.markerManager.selectedMarker.screenPos.x + 5, - (int)this.mw.markerManager.selectedMarker.screenPos.y, - true, - true - ); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - markerLabel.draw(new String[]{ - this.mc.thePlayer.getDisplayNameString(), - String.format("(%d, %d, %d)", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt)}, - null, - mouseX + 5, - mouseY, - true, - true - ); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, null, menuX, menuY, true, false); - this.optionsLabel.drawToRightOf(this.helpLabel, new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, true, false); - String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", - this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, new String[]{dimString}, true, false); - String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", - this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, new String[]{groupString}, true, false); - String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", - MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, new String[]{overlayString}, true, false); - - if (!VersionCheck.isLatestVersion()) { - String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", - VersionCheck.getLatestVersion()); - this.updateLabel.drawToRightOf(this.overlayLabel, new String[]{updateString}, true, false); - } - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - helpTooltipLabel.draw(HelpText1,HelpText2, 10 , 20, true, false); - } - if (this.updateLabel.posWithin(mouseX, mouseY)) { - updateTooltipLabel.draw(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20, true, false); - } - - MarkerOverlay.draw(); - - super.drawScreen(mouseX, mouseY, f); - } - - public void confirmClicked(boolean result, int id) { - if (id == 31102009) { - if (result) { - Utils.openWebLink(this.clickedLinkURI); - } - - this.clickedLinkURI = null; - this.mc.displayGuiScreen(this); - } - } -} +package mapwriter.gui; + +import java.awt.Point; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import mapwriter.Mw; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.config.WorldConfig; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import mapwriter.util.Logging; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import mapwriter.util.VersionCheck; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiConfirmOpenLink; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + public MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private String[] HelpText1 = new String[]{ + "Keys:", + "", + " Space", + " Delete", + " C", + " Home", + " End", + " N", + " T", + " P", + " R", + " U", + " L", + "", + "mw.gui.mwgui.helptext.1", + "mw.gui.mwgui.helptext.2", + "mw.gui.mwgui.helptext.3", + "mw.gui.mwgui.helptext.4", + "mw.gui.mwgui.helptext.5", + "mw.gui.mwgui.helptext.6", + "", + "mw.gui.mwgui.helptext.7", + "mw.gui.mwgui.helptext.8", + "mw.gui.mwgui.helptext.9" + }; + private String[] HelpText2 = new String[]{ + "", + "", + "mw.gui.mwgui.helptext.nextmarkergroup", + "mw.gui.mwgui.helptext.deletemarker", + "mw.gui.mwgui.helptext.cyclecolour", + "mw.gui.mwgui.helptext.centermap", + "mw.gui.mwgui.helptext.centermapplayer", + "mw.gui.mwgui.helptext.selectnextmarker", + "mw.gui.mwgui.helptext.teleport", + "mw.gui.mwgui.helptext.savepng", + "mw.gui.mwgui.helptext.regenerate", + "mw.gui.mwgui.helptext.undergroundmap", + "mw.gui.mwgui.helptext.markerlist" + }; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private MwGuiLabel helpLabel; + private MwGuiLabel optionsLabel; + private MwGuiLabel dimensionLabel; + private MwGuiLabel groupLabel; + private MwGuiLabel overlayLabel; + private MwGuiLabel updateLabel; + private MwGuiMarkerListOverlay MarkerOverlay; + + private MwGuiLabel helpTooltipLabel; + private MwGuiLabel updateTooltipLabel; + private MwGuiLabel statusLabel; + private MwGuiLabel markerLabel; + + public static MwGui instance; + + private URI clickedLinkURI; + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(); + this.mapView = new MapView(this.mw, true); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + + this.helpLabel = new MwGuiLabel(); + this.optionsLabel = new MwGuiLabel(); + this.dimensionLabel = new MwGuiLabel(); + this.groupLabel = new MwGuiLabel(); + this.overlayLabel = new MwGuiLabel(); + this.updateLabel = new MwGuiLabel(); + this.helpTooltipLabel = new MwGuiLabel(); + this.updateTooltipLabel = new MwGuiLabel(); + this.statusLabel = new MwGuiLabel(); + this.markerLabel = new MwGuiLabel(); + + this.MarkerOverlay = new MwGuiMarkerListOverlay(this, this.mw.markerManager); + + instance = this; + } + + public MwGui(Mw mw, int dim, int x, int z) { + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(Config.fullScreenZoomLevel); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() + { + MarkerOverlay.setDimensions(MarkerOverlay.listWidth, this.height - 20, MarkerOverlay.ListY, 10 + this.height - 20, this.width - 110); + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) + { + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click + // closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); + if ((worldDimension == this.mapView.getDimension()) + && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + // MwUtil.log("deleting marker %s", + // this.mw.markerManager.selectedMarker.name); + this.mw.markerManager + .delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir + .getName())); + + Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() + + "'"); + } + + public void regenerateView() { + Utils.printBoth(String.format( + I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + + " %dx%d " + + I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + + " (%d, %d)", + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); + // this.mw.reloadBlockColours(); + this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, + (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch (key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, + this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + this.centerOnSelectedMarker(); + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, + this.mapView, this.mouseBlockX, + Config.defaultTeleportHeight, this.mouseBlockZ)); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + case Keyboard.KEY_L: + this.MarkerOverlay.setEnabled(!this.MarkerOverlay.getEnabled()); + break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + this.exitGui(); + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(Config.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException { + if (this.MarkerOverlay.isMouseInField() && this.mouseLeftHeld == 0) + { + this.MarkerOverlay.handleMouseInput(); + } + else if (MwAPI.getCurrentDataProvider() != null && + MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) + { + return; + } + else + { + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height + / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) { + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (this.MarkerOverlay.isMouseInField() && this.mouseLeftHeld == 0) + { + this.MarkerOverlay.handleMouseInput(); + } + else + { + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, + this.mw, this.mapView, this.mapView.getDimension())); + } else if (this.optionsLabel.posWithin(x, y)) { + try { + GuiScreen newScreen = ModGuiConfig.class.getConstructor( + GuiScreen.class).newInstance(this); + this.mc.displayGuiScreen(newScreen); + } catch (Exception e) { + Logging.logError( + "There was a critical issue trying to build the config GUI for %s", + Reference.MOD_ID); + } + } else if (this.updateLabel.posWithin(x, y)) { + URI uri; + + if (!this.mc.gameSettings.chatLinks) { + return; + } + + try { + uri = new URI(VersionCheck.getUpdateURL()); + + if (!Reference.PROTOCOLS.contains(uri.getScheme().toLowerCase())) { + throw new URISyntaxException(uri.toString(), + "Unsupported protocol: " + + uri.getScheme().toLowerCase()); + } + + if (this.mc.gameSettings.chatLinksPrompt) { + this.clickedLinkURI = uri; + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, + uri.toString(), 31102009, false)); + } else { + Utils.openWebLink(uri); + } + } catch (URISyntaxException urisyntaxexception) { + Logging.logError("Can\'t open url for %s", + urisyntaxexception); + } + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + this.openMarkerGui(marker, x, y); + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, + y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), + blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + // this.viewSizeStart = this.mapManager.getViewSize(); + } + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseReleased(int x, int y, int button) { + // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + // this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) + && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, + n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated( + this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, + this.mouseBlockX, this.mouseBlockZ); + Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); + } + } + + //closes this gui + public void exitGui() + { + this.mc.displayGuiScreen((GuiScreen)null); + } + + /** + * Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() + { + Keyboard.enableRepeatEvents(false); + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + Keyboard.enableRepeatEvents(false); + } + + // called every frame + public void updateScreen() + { + } + + public void drawStatus(int bX, int bY, int bZ) + { + StringBuilder builder = new StringBuilder(); + if (bY != 0) { + builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ)); + } else { + builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ)); + } + + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) + { + builder.append(", " ); + builder.append(I18n.format("mw.gui.mwgui.status.biome", new Object[0])); + builder.append(String.format(": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); + } + } + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + { + builder.append(provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ)); + } + String s = builder.toString(); + int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); + + statusLabel.draw(new String[]{builder.toString()}, null, x, this.height - 21, true, false, this.width, this.height); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + // double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) + * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) + * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView + .getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart + - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart + - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, + this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + // this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, + this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + markerLabel.draw(new String[]{ + marker.name, + String.format("(%d, %d, %d)", + marker.x, + marker.y, + marker.z)}, + null, + mouseX + 5, + mouseY, + true, + true, + this.width, + this.height + ); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + markerLabel.draw(new String[]{ + this.mc.thePlayer.getDisplayNameString(), + String.format("(%d, %d, %d)", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt)}, + null, + mouseX + 5, + mouseY, + true, + true, + this.width, + this.height + ); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, null, menuX, menuY, true, false, this.width, this.height); + this.optionsLabel.drawToRightOf(this.helpLabel, new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, true, false, this.width, this.height); + String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", + this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, new String[]{dimString}, true, false, this.width, this.height); + String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", + this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, new String[]{groupString}, true, false, this.width, this.height); + String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", + MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, new String[]{overlayString}, true, false, this.width, this.height); + + if (!VersionCheck.isLatestVersion()) { + String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", + VersionCheck.getLatestVersion()); + this.updateLabel.drawToRightOf(this.overlayLabel, new String[]{updateString}, true, false, this.width, this.height); + } + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + helpTooltipLabel.draw(HelpText1,HelpText2, 10 , 20, true, false, this.width, this.height); + } + if (this.updateLabel.posWithin(mouseX, mouseY)) { + updateTooltipLabel.draw(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20, true, false, this.width, this.height); + } + + MarkerOverlay.drawScreen(mouseX, mouseY, f);; + + super.drawScreen(mouseX, mouseY, f); + } + + public void confirmClicked(boolean result, int id) { + if (id == 31102009) { + if (result) { + Utils.openWebLink(this.clickedLinkURI); + } + + this.clickedLinkURI = null; + this.mc.displayGuiScreen(this); + } + } + + public void centerOnSelectedMarker() + { + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, 0); + } + } + + public void openMarkerGui(Marker m, int mouseX, int mouseY) + { + if ((m != null) && (this.mw.markerManager.selectedMarker == m)) { + // right clicked previously selected marker. + // edit the marker + if (Config.newMarkerDialog) + { + this.mc.displayGuiScreen( + new MwGuiMarkerDialogNew(this, + this.mw.markerManager, m + ) + ); + } + else + { + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, m)); + } + + } else if (m == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = I18n.format("mw.gui.mwgui.group", new Object[0]); + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY + : Config.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + if (Config.newMarkerDialog) + { + this.mc.displayGuiScreen( + new MwGuiMarkerDialogNew( + this, + this.mw.markerManager, + "", + group, + mx, my, mz, + this.mapView.getDimension() + ) + ); + } + else + { + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, + this.mw.markerManager, "", group, mx, my, mz, + this.mapView.getDimension())); + } + } + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiLabel.java b/src/main/java/mapwriter/gui/MwGuiLabel.java index ae326e0d..17b52589 100644 --- a/src/main/java/mapwriter/gui/MwGuiLabel.java +++ b/src/main/java/mapwriter/gui/MwGuiLabel.java @@ -1,81 +1,74 @@ -package mapwriter.gui; - -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiScreen; - -public class MwGuiLabel -{ - int x = 0, y = 0, w = 1, h = 12; - int spacingX = 10; - int spacingY = 2; - private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; - private final GuiScreen parentScreen; - - public MwGuiLabel(GuiScreen parentScreen) - { - this.parentScreen = parentScreen; - } - - public void draw(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip) { - this.x = x; - this.y = y; - - int stringwidth = Utils.getMaxWidth(s1, s2); - this.w = stringwidth < parentScreen.width - 20 ? stringwidth : parentScreen.width - 20; - - String str = Utils.stringArrayToString(s1); - this.h = fontRendererObj.splitStringWidth(str, parentScreen.width); - - if (AllowFlip) - { - if (this.x + this.w + (spacingX * 2) > parentScreen.width) - { - this.x = this.x - this.w - spacingX - 5; - } - if (this.y + this.h + (spacingY * 2) > parentScreen.height) - { - this.y = this.y - this.h - spacingY; - } - } - - if (this.y + this.h + (spacingY * 2) > parentScreen.height) - { - return; - } - - if(Background) - { - Gui.drawRect(this.x, this.y, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); - } - - this.fontRendererObj.drawSplitString(str, this.x + 5 , this.y + 2, this.w, 0xffffff); - - if (s2 != null) - { - this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), this.x + 65, this.y + 2, this.w, 0xffffff); - } - } - - public void drawToRightOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { - this.draw(s, null, label.x + label.w + spacingX + 2, label.y, Background, AllowFlip); - } - - public void drawToLeftOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { - this.draw(s, null, label.x - label.w - spacingX + 2, label.y, Background, AllowFlip); - } - - public void drawToBelowOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { - this.draw(s, null, label.x, label.y + label.h + spacingY + 2, Background, AllowFlip); - } - - public void drawToAboveOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip) { - this.draw(s, null, label.x, label.y + label.h + spacingY + 2, Background, AllowFlip); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); - } -} +package mapwriter.gui; + +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; + +public class MwGuiLabel +{ + int x = 0, y = 0, w = 1, h = 12; + static int spacingX = 4; + static int spacingY = 2; + private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; + + + public MwGuiLabel() + { + } + //TODO: remove all vars to own methods + public void draw(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { + this.x = x; + this.y = y; + + int stringwidth = Utils.getMaxWidth(s1, s2); + this.w = stringwidth < parentWidth - 20 ? stringwidth : parentWidth - 20; + + String str = Utils.stringArrayToString(s1); + this.h = fontRendererObj.splitStringWidth(str, parentWidth); + + if (AllowFlip) + { + if (this.x + this.w + spacingX > parentWidth) + { + this.x = this.x - this.w - spacingX - 5; + } + if (this.y + this.h + spacingY > parentHeight) + { + this.y = this.y - this.h - spacingY; + } + } + + if(Background) + { + Gui.drawRect(this.x - spacingX, this.y - spacingY, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); + } + + this.fontRendererObj.drawSplitString(str, this.x , this.y, this.w, 0xffffff); + + if (s2 != null) + { + this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), this.x + 65, this.y, this.w, 0xffffff); + } + } + + public void drawToRightOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { + this.draw(s, null, label.x + label.w + (2 * spacingX) + 2, label.y, Background, AllowFlip, parentWidth, parentHeight); + } + + public void drawToLeftOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { + this.draw(s, null, label.x - label.w - (2 * spacingX) + 2, label.y, Background, AllowFlip, parentWidth, parentHeight); + } + + public void drawToBelowOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { + this.draw(s, null, label.x, label.y + label.h + (2 * spacingY) + 2, Background, AllowFlip, parentWidth, parentHeight); + } + + public void drawToAboveOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { + this.draw(s, null, label.x, label.y + label.h + (2 * spacingY) + 2, Background, AllowFlip, parentWidth, parentHeight); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x + spacingX) && (y >= this.y + spacingY) && (x <= (this.x + this.w + spacingX)) && (y <= (this.y + this.h + spacingY)); + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java index 4ba1b98d..83528863 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -1,65 +1,115 @@ -package mapwriter.gui; - -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; - -public class MwGuiMarkerListOverlay extends GuiScreen -{ - private final GuiScreen parentScreen; - private final MarkerManager markerManager; - - //TODO: Make the list scrollable and add button toggle on off - - public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManager) - { - this.parentScreen = parentScreen; - this.markerManager = markerManager; - this.fontRendererObj = Minecraft.getMinecraft().fontRendererObj; - } - - public void draw() - { - int x = parentScreen.width - 110; - int y = 10; - int w = 110 - 5; - int h = parentScreen.height - 20; - Boolean first = true; - MwGuiLabel prevLabel = new MwGuiLabel(this); - - this.width = w; - this.height = h; - - drawRect(x, y, x + w, h + y, 0x80000000); - y += 5; - for (Marker m : markerManager.visibleMarkerList) - { - - MwGuiLabel label = new MwGuiLabel(this); - - String[] text = new String[2]; - text[0] = m.name; - text[1] = String.format( - "(%d, %d, %d)", - m.x, - m.y, - m.z); - if (first) - { - label.draw(text, null, x, y, false, false); - first = false; - } - else - { - label.drawToBelowOf(prevLabel, text, false, false); - } - prevLabel = label; - - if (label.y + label.h + label.h> parentScreen.height) - { - break; - } - } - } -} +package mapwriter.gui; + +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; + +public class MwGuiMarkerListOverlay extends MwGuiSlot +{ + private final GuiScreen parentScreen; + private final MarkerManager markerManager; + + public static int listWidth = 95; + public static int ListY = 10; + private int height; + private int x; + + public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManager) + { + super( + Minecraft.getMinecraft(), //mcIn + listWidth, //width + parentScreen.height - 20, //height + ListY, //topIn + 10 + parentScreen.height - 20, //bottomIn + parentScreen.width - 110 //left + ); + + this.x = parentScreen.width - 110; + this.height = parentScreen.height - 20; + + this.parentScreen = parentScreen; + this.markerManager = markerManager; + } + + @Override + protected int getSlotHeight(int index) + { + String str = Utils.stringArrayToString(getLabelString(index)); + int height = mc.fontRendererObj.splitStringWidth(str, this.listWidth - 6); + + height += this.spacingY * 2; + + return height; + } + + protected String[] getLabelString(int index) + { + Marker m = markerManager.visibleMarkerList.get(index); + + String[] text = new String[2]; + text[0] = m.name; + text[1] = String.format( + "(%d, %d, %d)", + m.x, + m.y, + m.z); + return text; + } + + @Override + protected int getSize() + { + return markerManager.visibleMarkerList.size(); + } + + @Override + protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton) + { + markerManager.selectedMarker = markerManager.visibleMarkerList.get(slotIndex); + if (mouseButton == 1) + { + if (parentScreen instanceof MwGui) + { + ((MwGui)parentScreen).openMarkerGui(markerManager.selectedMarker, mouseX, mouseY);; + } + } + if (mouseButton == 0 && isDoubleClick) + { + if (parentScreen instanceof MwGui) + { + ((MwGui)parentScreen).centerOnSelectedMarker(); + } + } + } + + @Override + protected boolean isSelected(int slotIndex) + { + return markerManager.selectedMarker == markerManager.visibleMarkerList.get(slotIndex); + } + + @Override + protected void drawBackground() + { + } + + @Override + protected void drawSlot(int entryID, int x, int y, int slotHeight, int mouseXIn, int mouseYIn) + { + MwGuiLabel label = new MwGuiLabel(); + + label.draw(getLabelString(entryID), null, x, y, false, false, this.listWidth, this.height); + } + + @Override + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) + { + this.x = parentScreen.width - 110; + this.height = parentScreen.height - 20; + + super.setDimensions(widthIn, heightIn, topIn, bottomIn, left); + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiSlot.java b/src/main/java/mapwriter/gui/MwGuiSlot.java new file mode 100644 index 00000000..4cc54085 --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiSlot.java @@ -0,0 +1,554 @@ +package mapwriter.gui; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.util.MathHelper; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Mouse; + +@SideOnly(Side.CLIENT) +public abstract class MwGuiSlot +{ + protected final Minecraft mc; + public int width; + public int height; + /** The top of the slot container. Affects the overlays and scrolling. */ + public int top; + /** The bottom of the slot container. Affects the overlays and scrolling. */ + public int bottom; + public int right; + public int left; + public final int scrollBarWidth = 6; + /** The buttonID of the button used to scroll up */ + private int scrollUpButtonID; + /** The buttonID of the button used to scroll down */ + private int scrollDownButtonID; + protected int mouseX; + protected int mouseY; + protected boolean field_148163_i = true; + /** Where the mouse was in the window when you first clicked to scroll */ + protected float initialClickY = -2.0F; + /** + * What to multiply the amount you moved your mouse by (used for slowing down scrolling when over the items and not + * on the scroll bar) + */ + protected float scrollMultiplier; + /** How far down this slot has been scrolled */ + protected float amountScrolled; + /** The element in the list that was selected */ + protected int selectedElement = -1; + /** The time when this button was last clicked. */ + protected long lastClicked; + /** Set to true if a selected element in this gui will show an outline box */ + protected boolean showSelectionBox = true; + protected boolean hasListHeader; + public int headerPadding; + private boolean enabled = false; + private static final String __OBFID = "CL_00000679"; + int spacingY = 4; + + public MwGuiSlot(Minecraft mcIn, int width, int height, int topIn, int bottomIn, int left) + { + this.mc = mcIn; + this.width = width; + this.height = height; + this.top = topIn; + this.bottom = bottomIn; + this.left = left; + this.right = left + width; + } + + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) + { + this.width = widthIn; + this.height = heightIn; + this.top = topIn; + this.bottom = bottomIn; + this.left = left; + this.right = left + widthIn; + } + + public void setShowSelectionBox(boolean showSelectionBoxIn) + { + this.showSelectionBox = showSelectionBoxIn; + } + + /** + * Sets hasListHeader and headerHeight. Params: hasListHeader, headerHeight. If hasListHeader is false headerHeight + * is set to 0. + */ + protected void setHasListHeader(boolean hasListHeaderIn, int headerPaddingIn) + { + this.hasListHeader = hasListHeaderIn; + this.headerPadding = headerPaddingIn; + + if (!hasListHeaderIn) + { + this.headerPadding = 0; + } + } + + protected abstract int getSize(); + + /** + * The element in the slot that was clicked, boolean for whether it was double clicked or not + */ + protected abstract void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton); + + /** + * Returns true if the element passed in is currently selected + */ + protected abstract boolean isSelected(int slotIndex); + + /** + * + * @param index of the item + * @return the slotheigt of the specific item + */ + protected abstract int getSlotHeight(int index); + + /** + * Return the height of the content being scrolled + */ + protected int getContentHeight() + { + int slotHeight = this.headerPadding; + for (int index = 0; index < this.getSize(); ++index) + { + slotHeight += this.getSlotHeight(index); + } + + return slotHeight; + } + + protected abstract void drawBackground(); + + protected void slotOutOfBounds(int index, int p_178040_2_, int p_178040_3_) {} + + protected abstract void drawSlot(int entryID, int x, int y, int h, int mouseXIn, int mouseYIn); + + /** + * Handles drawing a list's header row. + */ + protected void drawListHeader(int x, int y, Tessellator tess) {} + + protected void func_148132_a(int p_148132_1_, int p_148132_2_) {} + + protected void func_148142_b(int p_148142_1_, int p_148142_2_) {} + + public int getSlotIndexFromScreenCoords(int x, int y) + { + int k = this.left + (this.width / 2 - this.getListWidth() / 2); + int l = this.left + (this.width / 2 + this.getListWidth() / 2) - this.scrollBarWidth; + int i1 = y - this.top - this.headerPadding + (int)this.amountScrolled; + + int yStart = 0; + int yStop = yStart + this.getSlotHeight(0); + + for (int index = 0; index < this.getSize(); ++index) + { + if (i1 >= yStart && i1 <= yStop) + { + return x < this.getScrollBarX() && x >= k && x <= l && i1 >= 0 ? index : -1; + } + yStart = yStop; + yStop += this.getSlotHeight(index + 1); + } + return -1; + } + + /** + * Registers the IDs that can be used for the scrollbar's up/down buttons. + */ + public void registerScrollButtons(int scrollUpButtonIDIn, int scrollDownButtonIDIn) + { + this.scrollUpButtonID = scrollUpButtonIDIn; + this.scrollDownButtonID = scrollDownButtonIDIn; + } + + /** + * Stop the thing from scrolling out of bounds + */ + protected void bindAmountScrolled() + { + int i = this.func_148135_f(); + + if (i < 0) + { + i /= 2; + } + + if (!this.field_148163_i && i < 0) + { + i = 0; + } + + this.amountScrolled = MathHelper.clamp_float(this.amountScrolled, 0.0F, (float)i); + } + + public int func_148135_f() + { + return Math.max(0, this.getContentHeight() - (this.bottom - this.top)); + } + + /** + * Returns the amountScrolled field as an integer. + */ + public int getAmountScrolled() + { + return (int)this.amountScrolled; + } + + public boolean isMouseYWithinSlotBounds() + { + return this.mouseY >= this.top && this.mouseY <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; + } + + public boolean isMouseXWithinSlotBounds() + { + return this.mouseX >= this.left && this.mouseX <= this.right; + } + + public boolean isMouseInField() + { + return this.isMouseYWithinSlotBounds() && this.isMouseXWithinSlotBounds(); + } + + /** + * Scrolls the slot by the given amount. A positive value scrolls down, and a negative value scrolls up. + */ + public void scrollBy(int amount) + { + this.amountScrolled += (float)amount; + this.bindAmountScrolled(); + this.initialClickY = -2.0F; + } + + public void actionPerformed(GuiButton button) + { + if (button.enabled) + { + int slotHeight = this.getAverageSlotHeight(); + if (button.id == this.scrollUpButtonID) + { + this.amountScrolled -= (float)(slotHeight * 2 / 3); + this.initialClickY = -2.0F; + this.bindAmountScrolled(); + } + else if (button.id == this.scrollDownButtonID) + { + this.amountScrolled += (float)(slotHeight * 2 / 3); + this.initialClickY = -2.0F; + this.bindAmountScrolled(); + } + } + } + + public void drawScreen(int mouseXIn, int mouseYIn, float f) + { + if (this.getEnabled()) + { + this.mouseX = mouseXIn; + this.mouseY = mouseYIn; + this.drawBackground(); + int k = this.getScrollBarX(); + int l = k + this.scrollBarWidth; + this.bindAmountScrolled(); + GlStateManager.disableLighting(); + GlStateManager.disableFog(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.drawContainerBackground(tessellator); + int i1 = this.left + (this.width / 2 - this.getListWidth() / 2); + int j1 = this.top - (int)this.amountScrolled; + + if (this.hasListHeader) + { + this.drawListHeader(i1, j1, tessellator); + } + + this.drawSelectionBox(i1, j1, mouseXIn, mouseYIn); + GlStateManager.disableDepth(); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1); + GlStateManager.disableAlpha(); + GlStateManager.shadeModel(7425); + GlStateManager.disableTexture2D(); + + int k1 = this.func_148135_f(); + + if (k1 > 0) + { + int l1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); + l1 = MathHelper.clamp_int(l1, 32, this.bottom - this.top - 8); + int i2 = (int)this.amountScrolled * (this.bottom - this.top - l1) / k1 + this.top; + + if (i2 < this.top) + { + i2 = this.top; + } + //draw the scrollbar + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(0, 255); + worldrenderer.addVertexWithUV((double)k, (double)this.bottom, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double)l, (double)this.bottom, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double)l, (double)this.top, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double)k, (double)this.top, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(8421504, 255); + worldrenderer.addVertexWithUV((double)k, (double)(i2 + l1), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double)l, (double)(i2 + l1), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double)l, (double)i2, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double)k, (double)i2, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(12632256, 255); + worldrenderer.addVertexWithUV((double)k, (double)(i2 + l1 - 1), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double)(l - 1), (double)(i2 + l1 - 1), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double)(l - 1), (double)i2, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double)k, (double)i2, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + } + + this.func_148142_b(mouseXIn, mouseYIn); + GlStateManager.enableTexture2D(); + GlStateManager.shadeModel(7424); + GlStateManager.enableAlpha(); + GlStateManager.disableBlend(); + } + } + + public void handleMouseInput() + { + if (this.isMouseInField()) + { + if (Mouse.isButtonDown(0) && this.getEnabled()) + { + if (this.initialClickY == -1.0F) + { + boolean flag = true; + + if (this.mouseY >= this.top && this.mouseY <= this.bottom) + { + int i = (this.width / 2 - this.getListWidth() / 2) + this.left; + int j = (this.width / 2 + this.getListWidth() / 2) + this.left - this.scrollBarWidth; + int k = this.mouseY - this.top - this.headerPadding + (int)this.amountScrolled; + int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); + + if (this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) + { + boolean flag1 = l == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; + this.elementClicked(l, flag1, this.mouseX, this.mouseY, 0); + this.selectedElement = l; + this.lastClicked = Minecraft.getSystemTime(); + } + else if (this.mouseX >= i && this.mouseX <= j && k < 0) + { + this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int)this.amountScrolled); + flag = false; + } + + int i2 = this.getScrollBarX(); + int i1 = i2 + this.scrollBarWidth; + + if (this.mouseX >= i2 && this.mouseX <= i1) + { + this.scrollMultiplier = -1.0F; + int j1 = this.func_148135_f(); + + if (j1 < 1) + { + j1 = 1; + } + + int k1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); + k1 = MathHelper.clamp_int(k1, 32, this.bottom - this.top - 8); + this.scrollMultiplier /= (float)(this.bottom - this.top - k1) / (float)j1; + } + else + { + this.scrollMultiplier = 1.0F; + } + + if (flag) + { + this.initialClickY = (float)this.mouseY; + } + else + { + this.initialClickY = -2.0F; + } + } + else + { + this.initialClickY = -2.0F; + } + } + else if (this.initialClickY >= 0.0F) + { + this.amountScrolled -= ((float)this.mouseY - this.initialClickY) * this.scrollMultiplier; + this.initialClickY = (float)this.mouseY; + } + } + else + { + this.initialClickY = -1.0F; + } + + if (Mouse.isButtonDown(1) && this.getEnabled()) + { + if (this.initialClickY == -1.0F) + { + boolean flag = true; + + if (this.mouseY >= this.top && this.mouseY <= this.bottom) + { + int i = (this.width / 2 - this.getListWidth() / 2) + this.left; + int j = (this.width / 2 + this.getListWidth() / 2) + this.left - this.scrollBarWidth; + int k = this.mouseY - this.top - this.headerPadding + (int)this.amountScrolled; + int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); + + if (this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) + { + boolean flag1 = l == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; + this.elementClicked(l, flag1, this.mouseX, this.mouseY, 1); + this.selectedElement = l; + this.lastClicked = Minecraft.getSystemTime(); + } + else if (this.mouseX >= i && this.mouseX <= j && k < 0) + { + this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int)this.amountScrolled); + flag = false; + } + } + } + } + + int l1 = Mouse.getEventDWheel(); + + if (l1 != 0) + { + if (l1 > 0) + { + l1 = -1; + } + else if (l1 < 0) + { + l1 = 1; + } + + this.amountScrolled += (float)(l1 * this.getAverageSlotHeight() / 2); + } + } + } + + public void setEnabled(boolean enabledIn) + { + this.enabled = enabledIn; + } + + public boolean getEnabled() + { + return this.enabled; + } + + /** + * Gets the width of the list + */ + public int getListWidth() + { + return this.width; + } + + /** + * Draws the selection box around the selected slot element. + */ + protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) + { + int i1 = this.getSize(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + int yTotal = y + this.headerPadding; + + for (int index = 0; index < i1; ++index) + { + int slotHeight = getSlotHeight(index); + + if (yTotal + slotHeight > this.bottom || yTotal < this.top) + { + this.slotOutOfBounds(index, x, yTotal); + yTotal += slotHeight; + continue; + } + + if (this.showSelectionBox && this.isSelected(index)) + { + int xLeft = this.left + (this.width / 2 - this.getListWidth() / 2); + int xRight = this.left + (this.width / 2 + this.getListWidth() / 2) - this.scrollBarWidth; + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableTexture2D(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorOpaque_I(8421504); + worldrenderer.addVertexWithUV((double)xLeft, (double)(yTotal + slotHeight), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double)xRight, (double)(yTotal + slotHeight), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double)xRight, (double)(yTotal), 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double)xLeft, (double)(yTotal), 0.0D, 0.0D, 0.0D); + worldrenderer.setColorOpaque_I(0); + worldrenderer.addVertexWithUV((double)(xLeft + 1), (double)(yTotal + slotHeight - 1), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double)(xRight - 1), (double)(yTotal + slotHeight - 1), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double)(xRight - 1), (double)(yTotal + 1), 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double)(xLeft + 1), (double)(yTotal + 1), 0.0D, 0.0D, 0.0D); + tessellator.draw(); + GlStateManager.enableTexture2D(); + } + + this.drawSlot(index, x + 4, yTotal + this.spacingY, slotHeight, mouseXIn, mouseYIn); + + yTotal += slotHeight; + } + } + + protected int getScrollBarX() + { + return left + this.width - this.scrollBarWidth; + } + + /** + * Sets the left and right bounds of the slot. Param is the left bound, right is calculated as left + width. + */ + public void setSlotXBoundsFromLeft(int leftIn) + { + this.left = leftIn; + this.right = leftIn + this.width; + } + + public int getAverageSlotHeight() + { + int height = 0; + int biggest = 0; + for (int index = 0; index < this.getSize(); ++index) + { + int slotheight = this.getSlotHeight(index); + height += slotheight; + + biggest = biggest < slotheight ? slotheight : biggest; + } + + return height > 0 ? height / this.getSize() : 9; + } + + protected void drawContainerBackground(Tessellator tessellator) + { + Gui.drawRect(left, top, right, bottom, 0x80000000); + } +} \ No newline at end of file diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index f1c5d5ac..d9dee529 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -1,148 +1,152 @@ -# Keys -key.mw_open_gui=Open map GUI -key.mw_new_marker=New Waypoint -key.mw_next_map_mode=Next map mode -key.mw_next_marker_group=Next waypoint group -key.mw_teleport=Teleport to waypoint -key.mw_zoom_in=Minimap zoom in -key.mw_zoom_out=Minimap zoom out -key.mw_underground_mode=Underground map mode - -#Config Global -mw.config.linearTextureScaling=Linear texture scaling enabled -mw.config.linearTextureScaling.tooltip=Enabled linear texture scaling. (nearest is used otherwise) -mw.config.useSavedBlockColours= Use saved block colors -mw.config.useSavedBlockColours.tooltip= -mw.config.teleportEnabled= Teleport enabled -mw.config.teleportEnabled.tooltip=Enables teleporting to positions on the map -mw.config.teleportCommand=Teleport Command -mw.config.teleportCommand.tooltip=The command used to teleport the player - -mw.config.maxChunkSaveDistSq=Max draw distance -mw.config.maxChunkSaveDistSq.tooltip=The square of the max distance from the player to map chunks at -mw.config.mapPixelSnapEnabled= Map pixel snap -mw.config.mapPixelSnapEnabled.tooltip= -mw.config.maxDeathMarkers=Max death markers -mw.config.maxDeathMarkers.tooltip=The maximum amount of death markers -mw.config.chunksPerTick=Chunks per tick -mw.config.chunksPerTick.tooltip=sets the maximum number of chunks updated per tick -mw.config.saveDirOverride=Save directory Override -mw.config.saveDirOverride.tooltip=Override the directory MapWriter uses to store images and region -mw.config.portNumberInWorldNameEnabled=Portnumber in world Name -mw.config.portNumberInWorldNameEnabled.tooltip=set to false to disable appending the port number to the world name for multiplayer worlds -mw.config.undergroundMode=Underground Mode -mw.config.undergroundMode.tooltip=Enables the underground mode -mw.config.regionFileOutputEnabledSP=Region file output SP -mw.config.regionFileOutputEnabledSP.tooltip=set to false to disable saving region files (mca files) in single player. prevents map regen if disabled -mw.config.regionFileOutputEnabledMP=Region file output MP -mw.config.regionFileOutputEnabledMP.tooltip=set to false to disable saving region files (mca files) in multiplayer. prevents map regen if disabled -mw.config.backgroundTextureMode= -mw.config.backgroundTextureMode.tooltip= -mw.config.zoomOutLevels=Zoom out levels -mw.config.zoomOutLevels.tooltip=Max number of steps you can zoom out. Larger values decrease performance. -mw.config.zoomInLevels=Zoom in levels -mw.config.zoomInLevels.tooltip=Max number of steps you can zoom in. Does not affect performance. -mw.config.textureSize= -mw.config.textureSize.tooltip= -mw.config.moreRealisticMap=Enables realistic map -mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic -mw.config.newMarkerDialog=New Marker Dialog -mw.config.newMarkerDialog.tooltip=Enable to use the new marker dialog -mw.config.useFeetHeight=Use feet height -mw.config.useFeetHeight.tooltip=Have cordinates show feet height instead of head height - - -#Config Temp -mw.config.overlayModeIndex= -mw.config.overlayModeIndex.tooltip= -mw.config.overlayZoomLevel= -mw.config.overlayZoomLevel.tooltip= - -#Config map -mw.config.map.enabled=Map enabled -mw.config.map.enabled.tooltip=Set to false to disable this map view -mw.config.map.playerArrowSize=Player arrow Size -mw.config.map.playerArrowSize.tooltip=The size of the player arrow on the map -mw.config.map.markerSize=Marker size -mw.config.map.markerSize.tooltip=The size of markers on the map -mw.config.map.alphaPercent= Map opacity -mw.config.map.alphaPercent.tooltip=Map opacity. 0-100 percent -mw.config.map.heightPercent= -mw.config.map.heightPercent.tooltip=The map size as a percentage of the screen height. Ignored if both Left and Right or Bottom and Top margins are set. -mw.config.map.marginTop=Top margin -mw.config.map.marginTop.tooltip= -mw.config.map.marginBottom=Bottom margin -mw.config.map.marginBottom.tooltip= -mw.config.map.marginLeft=Left margin -mw.config.map.marginLeft.tooltip= -mw.config.map.marginRight=Right margin -mw.config.map.marginRight.tooltip= -mw.config.map.rotate=Rotate map -mw.config.map.rotate.tooltip=Set to true to rotate the map, only possible in circular mode -mw.config.map.circular=Circular map -mw.config.map.circular.tooltip=True = Circular map, false = square map -mw.config.map.coordsEnabled=Enable coordinates -mw.config.map.coordsEnabled.tooltip=set to true to display coordinates under map -mw.config.map.borderMode=Draw border -mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map -mw.config.map.trailMarkerSize=Trail marker size -mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map - -mw.config.coordsMode= Coordinates mode -mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap - -#Gui -mw.gui.mwgui.help=Help -mw.gui.mwgui.options=Options -mw.gui.mwgui.dimension=dimension -mw.gui.mwgui.group=group -mw.gui.mwgui.overlay=overlay -mw.gui.mwgui.newversion=New version -mw.gui.mwgui.helptext.1=Left click drag or arrow keys pan the map. -mw.gui.mwgui.helptext.2=Mouse wheel or Page Up/Down zooms map. -mw.gui.mwgui.helptext.3=Right click map to create a new marker. -mw.gui.mwgui.helptext.4=Left click drag a selected marker to move it. -mw.gui.mwgui.helptext.5=Mouse wheel over selected marker to cycle colour. -mw.gui.mwgui.helptext.6=Mouse wheel over dimension or group box to cycle. -mw.gui.mwgui.helptext.nextmarkergroup=Next marker group -mw.gui.mwgui.helptext.deletemarker=Delete selected marker -mw.gui.mwgui.helptext.cyclecolour=Cycle selected marker colour -mw.gui.mwgui.helptext.centermap=Centre map on player -mw.gui.mwgui.helptext.centermapplayer=Centre map on selected marker -mw.gui.mwgui.helptext.selectnextmarker=Select next marker -mw.gui.mwgui.helptext.teleport=Teleport to cursor or selected marker -mw.gui.mwgui.helptext.savepng=Save PNG of visible map area -mw.gui.mwgui.helptext.regenerate=Regenerate visible map area from region files -mw.gui.mwgui.helptext.undergroundmap=Underground map mode -mw.gui.mwgui.status.biome=biome -mw.gui.mwgui.status.cursor=cursor -mw.gui.mwgui.chatmsg.regenmap.1=regenerating -mw.gui.mwgui.group=group -mw.gui.mwgui.chatmsg.regenmap.2=blocks starting from -mw.gui.mwgui.chatmsg.merge=merging to - -mw.gui.mwguidimensiondialog.title=Set dimension to -mw.gui.mwguidimensiondialog.error=invalid dimension - -mw.gui.mwguimarkerdialog.title.new=Marker Name -mw.gui.mwguimarkerdialog.title.edit=Edit Marker Name -mw.gui.mwguimarkerdialog.error=marker must have a name -mw.gui.mwguimarkerdialog.title.group=Marker Group -mw.gui.mwguimarkerdialog.error.group=marker must have a group name -mw.gui.mwguimarkerdialog.title.x=Marker X -mw.gui.mwguimarkerdialog.error.x=invalid value -mw.gui.mwguimarkerdialog.title.y=Marker Y -mw.gui.mwguimarkerdialog.error.y=invalid value -mw.gui.mwguimarkerdialog.title.z=Marker Z -mw.gui.mwguimarkerdialog.error.z=invalid value - -mw.gui.mwguimarkerdialognew.title.new=Add New Marker -mw.gui.mwguimarkerdialognew.title.edit=Edit Marker -mw.gui.mwguimarkerdialognew.editMarkerName=Name -mw.gui.mwguimarkerdialognew.editMarkerGroup=Group -mw.gui.mwguimarkerdialognew.editMarkerX=X -mw.gui.mwguimarkerdialognew.editMarkerY=Y -mw.gui.mwguimarkerdialognew.editMarkerZ=Z - -mw.gui.mwguimarkerdialognew.title=Teleport Height +# Keys +key.mw_open_gui=Open map GUI +key.mw_new_marker=New Waypoint +key.mw_next_map_mode=Next map mode +key.mw_next_marker_group=Next waypoint group +key.mw_teleport=Teleport to waypoint +key.mw_zoom_in=Minimap zoom in +key.mw_zoom_out=Minimap zoom out +key.mw_underground_mode=Underground map mode + +#Config Global +mw.config.linearTextureScaling=Linear texture scaling enabled +mw.config.linearTextureScaling.tooltip=Enabled linear texture scaling. (nearest is used otherwise) +mw.config.useSavedBlockColours= Use saved block colors +mw.config.useSavedBlockColours.tooltip= +mw.config.teleportEnabled= Teleport enabled +mw.config.teleportEnabled.tooltip=Enables teleporting to positions on the map +mw.config.teleportCommand=Teleport Command +mw.config.teleportCommand.tooltip=The command used to teleport the player + +mw.config.maxChunkSaveDistSq=Max draw distance +mw.config.maxChunkSaveDistSq.tooltip=The square of the max distance from the player to map chunks at +mw.config.mapPixelSnapEnabled= Map pixel snap +mw.config.mapPixelSnapEnabled.tooltip= +mw.config.maxDeathMarkers=Max death markers +mw.config.maxDeathMarkers.tooltip=The maximum amount of death markers +mw.config.chunksPerTick=Chunks per tick +mw.config.chunksPerTick.tooltip=sets the maximum number of chunks updated per tick +mw.config.saveDirOverride=Save directory Override +mw.config.saveDirOverride.tooltip=Override the directory MapWriter uses to store images and region +mw.config.portNumberInWorldNameEnabled=Portnumber in world Name +mw.config.portNumberInWorldNameEnabled.tooltip=set to false to disable appending the port number to the world name for multiplayer worlds +mw.config.undergroundMode=Underground Mode +mw.config.undergroundMode.tooltip=Enables the underground mode +mw.config.regionFileOutputEnabledSP=Region file output SP +mw.config.regionFileOutputEnabledSP.tooltip=set to false to disable saving region files (mca files) in single player. prevents map regen if disabled +mw.config.regionFileOutputEnabledMP=Region file output MP +mw.config.regionFileOutputEnabledMP.tooltip=set to false to disable saving region files (mca files) in multiplayer. prevents map regen if disabled +mw.config.backgroundTextureMode= +mw.config.backgroundTextureMode.tooltip= +mw.config.zoomOutLevels=Zoom out levels +mw.config.zoomOutLevels.tooltip=Max number of steps you can zoom out. Larger values decrease performance. +mw.config.zoomInLevels=Zoom in levels +mw.config.zoomInLevels.tooltip=Max number of steps you can zoom in. Does not affect performance. +mw.config.textureSize= +mw.config.textureSize.tooltip= +mw.config.moreRealisticMap=Enables realistic map +mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic +mw.config.newMarkerDialog=New Marker Dialog +mw.config.newMarkerDialog.tooltip=Enable to use the new marker dialog +mw.config.useFeetHeight=Use feet height +mw.config.useFeetHeight.tooltip=Have cordinates show feet height instead of head height + + +#Config Temp +mw.config.overlayModeIndex= +mw.config.overlayModeIndex.tooltip= +mw.config.overlayZoomLevel= +mw.config.overlayZoomLevel.tooltip= + +#Config map +mw.config.map.enabled=Map enabled +mw.config.map.enabled.tooltip=Set to false to disable this map view +mw.config.map.playerArrowSize=Player arrow Size +mw.config.map.playerArrowSize.tooltip=The size of the player arrow on the map +mw.config.map.markerSize=Marker size +mw.config.map.markerSize.tooltip=The size of markers on the map +mw.config.map.alphaPercent= Map opacity +mw.config.map.alphaPercent.tooltip=Map opacity. 0-100 percent +mw.config.map.heightPercent= +mw.config.map.heightPercent.tooltip=The map size as a percentage of the screen height. Ignored if both Left and Right or Bottom and Top margins are set. +mw.config.map.marginTop=Top margin +mw.config.map.marginTop.tooltip= +mw.config.map.marginBottom=Bottom margin +mw.config.map.marginBottom.tooltip= +mw.config.map.marginLeft=Left margin +mw.config.map.marginLeft.tooltip= +mw.config.map.marginRight=Right margin +mw.config.map.marginRight.tooltip= +mw.config.map.rotate=Rotate map +mw.config.map.rotate.tooltip=Set to true to rotate the map, only possible in circular mode +mw.config.map.circular=Circular map +mw.config.map.circular.tooltip=True = Circular map, false = square map +mw.config.map.coordsEnabled=Enable coordinates +mw.config.map.coordsEnabled.tooltip=set to true to display coordinates under map +mw.config.map.borderMode=Draw border +mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map +mw.config.map.trailMarkerSize=Trail marker size +mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map + +mw.config.coordsMode= Coordinates mode +mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap + +#Gui +mw.gui.mwgui.help=Help +mw.gui.mwgui.options=Options +mw.gui.mwgui.dimension=dimension +mw.gui.mwgui.group=group +mw.gui.mwgui.overlay=overlay +mw.gui.mwgui.newversion=New version +mw.gui.mwgui.helptext.1=Left click drag or arrow keys pan the map. +mw.gui.mwgui.helptext.2=Mouse wheel or Page Up/Down zooms map. +mw.gui.mwgui.helptext.3=Right click map to create a new marker. +mw.gui.mwgui.helptext.4=Left click drag a selected marker to move it. +mw.gui.mwgui.helptext.5=Mouse wheel over selected marker to cycle colour. +mw.gui.mwgui.helptext.6=Mouse wheel over dimension or group box to cycle. +mw.gui.mwgui.helptext.7=Right click marker in the List to edit the marker +mw.gui.mwgui.helptext.8=Double click marker in the list to center screen on the marker +mw.gui.mwgui.helptext.9=Left click marker in the list to select the marker +mw.gui.mwgui.helptext.nextmarkergroup=Next marker group +mw.gui.mwgui.helptext.deletemarker=Delete selected marker +mw.gui.mwgui.helptext.cyclecolour=Cycle selected marker colour +mw.gui.mwgui.helptext.centermap=Centre map on player +mw.gui.mwgui.helptext.centermapplayer=Centre map on selected marker +mw.gui.mwgui.helptext.selectnextmarker=Select next marker +mw.gui.mwgui.helptext.teleport=Teleport to cursor or selected marker +mw.gui.mwgui.helptext.savepng=Save PNG of visible map area +mw.gui.mwgui.helptext.regenerate=Regenerate visible map area from region files +mw.gui.mwgui.helptext.undergroundmap=Underground map mode +mw.gui.mwgui.helptext.markerlist=Shows the markerlist +mw.gui.mwgui.status.biome=biome +mw.gui.mwgui.status.cursor=cursor +mw.gui.mwgui.chatmsg.regenmap.1=regenerating +mw.gui.mwgui.group=group +mw.gui.mwgui.chatmsg.regenmap.2=blocks starting from +mw.gui.mwgui.chatmsg.merge=merging to + +mw.gui.mwguidimensiondialog.title=Set dimension to +mw.gui.mwguidimensiondialog.error=invalid dimension + +mw.gui.mwguimarkerdialog.title.new=Marker Name +mw.gui.mwguimarkerdialog.title.edit=Edit Marker Name +mw.gui.mwguimarkerdialog.error=marker must have a name +mw.gui.mwguimarkerdialog.title.group=Marker Group +mw.gui.mwguimarkerdialog.error.group=marker must have a group name +mw.gui.mwguimarkerdialog.title.x=Marker X +mw.gui.mwguimarkerdialog.error.x=invalid value +mw.gui.mwguimarkerdialog.title.y=Marker Y +mw.gui.mwguimarkerdialog.error.y=invalid value +mw.gui.mwguimarkerdialog.title.z=Marker Z +mw.gui.mwguimarkerdialog.error.z=invalid value + +mw.gui.mwguimarkerdialognew.title.new=Add New Marker +mw.gui.mwguimarkerdialognew.title.edit=Edit Marker +mw.gui.mwguimarkerdialognew.editMarkerName=Name +mw.gui.mwguimarkerdialognew.editMarkerGroup=Group +mw.gui.mwguimarkerdialognew.editMarkerX=X +mw.gui.mwguimarkerdialognew.editMarkerY=Y +mw.gui.mwguimarkerdialognew.editMarkerZ=Z + +mw.gui.mwguimarkerdialognew.title=Teleport Height mw.gui.mwguimarkerdialognew.error=invalid height \ No newline at end of file From 264625e437230f361ea5904d673e9c9ff1f60d09 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 7 Sep 2015 19:34:26 +0200 Subject: [PATCH 071/109] some updates to the label class to remove all the calculation from the draw method. --- src/main/java/mapwriter/gui/MwGui.java | 246 ++++++++++++++---- src/main/java/mapwriter/gui/MwGuiLabel.java | 201 +++++++++++--- .../mapwriter/gui/MwGuiMarkerListOverlay.java | 4 +- 3 files changed, 358 insertions(+), 93 deletions(-) diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 5c70e788..bf5d06cb 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -127,16 +127,7 @@ public MwGui(Mw mw) { this.mw.playerDimension); this.mapView.setZoomLevel(Config.fullScreenZoomLevel); - this.helpLabel = new MwGuiLabel(); - this.optionsLabel = new MwGuiLabel(); - this.dimensionLabel = new MwGuiLabel(); - this.groupLabel = new MwGuiLabel(); - this.overlayLabel = new MwGuiLabel(); - this.updateLabel = new MwGuiLabel(); - this.helpTooltipLabel = new MwGuiLabel(); - this.updateTooltipLabel = new MwGuiLabel(); - this.statusLabel = new MwGuiLabel(); - this.markerLabel = new MwGuiLabel(); + this.initLabels(); this.MarkerOverlay = new MwGuiMarkerListOverlay(this, this.mw.markerManager); @@ -154,9 +145,141 @@ public MwGui(Mw mw, int dim, int x, int z) { // is resized public void initGui() { + this.helpLabel.setParentWidthAndHeight(this.width, this.height); + this.optionsLabel.setParentWidthAndHeight(this.width, this.height); + this.dimensionLabel.setParentWidthAndHeight(this.width, this.height); + this.groupLabel.setParentWidthAndHeight(this.width, this.height); + this.overlayLabel.setParentWidthAndHeight(this.width, this.height); + this.updateLabel.setParentWidthAndHeight(this.width, this.height); + + this.helpTooltipLabel.setParentWidthAndHeight(this.width, this.height); + this.updateTooltipLabel.setParentWidthAndHeight(this.width, this.height); + this.statusLabel.setParentWidthAndHeight(this.width, this.height); + this.markerLabel.setParentWidthAndHeight(this.width, this.height); + MarkerOverlay.setDimensions(MarkerOverlay.listWidth, this.height - 20, MarkerOverlay.ListY, 10 + this.height - 20, this.width - 110); } + public void initLabels() + { + this.helpLabel = new MwGuiLabel( + new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, + null, + menuX, + menuY, + true, + false, + this.width, + this.height + ); + this.optionsLabel = new MwGuiLabel( + new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + this.dimensionLabel = new MwGuiLabel( + null, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + this.groupLabel = new MwGuiLabel( + null, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + this.overlayLabel = new MwGuiLabel( + null, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + String updateString = String.format( + "[" + I18n.format("mw.gui.mwgui.newversion", + new Object[0]) + ": %s]", + VersionCheck.getLatestVersion() + ); + this.updateLabel = new MwGuiLabel( + new String[]{updateString}, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + this.helpTooltipLabel = new MwGuiLabel( + HelpText1, + HelpText2, + 0, + 0, + true, + false, + this.width, + this.height + ); + + this.updateTooltipLabel = new MwGuiLabel( + new String[]{VersionCheck.getUpdateURL()}, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + + this.statusLabel = new MwGuiLabel( + null, + null, + 0, + 0, + true, + false, + this.width, + this.height + ); + this.markerLabel = new MwGuiLabel( + null, + null, + 0, + 0, + true, + true, + this.width, + this.height + ); + + this.optionsLabel.drawToRightOf(this.helpLabel); + this.dimensionLabel.drawToRightOf(this.optionsLabel); + this.groupLabel.drawToRightOf(this.dimensionLabel); + this.overlayLabel.drawToRightOf(this.groupLabel); + this.updateLabel.drawToRightOf(this.overlayLabel); + + this.helpTooltipLabel.drawToBelowOf(this.helpLabel); + this.updateTooltipLabel.drawToBelowOf(this.helpLabel); + } + // called when a button is pressed protected void actionPerformed(GuiButton button) { @@ -543,7 +666,9 @@ public void drawStatus(int bX, int bY, int bZ) String s = builder.toString(); int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); - statusLabel.draw(new String[]{builder.toString()}, null, x, this.height - 21, true, false, this.width, this.height); + this.statusLabel.setCoords(x, this.height - 21); + this.statusLabel.setText(new String[]{builder.toString()}, null); + statusLabel.draw(); } // also called every frame @@ -590,78 +715,89 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); + //draw the label near mousepointer + this.drawMarkerLabel(mouseX, mouseY, f); + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.drawLabel(mouseX, mouseY, f); + + MarkerOverlay.drawScreen(mouseX, mouseY, f);; + + super.drawScreen(mouseX, mouseY, f); + } + + private void drawMarkerLabel(int mouseX, int mouseY, float f) + { // draw name of marker under mouse cursor Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); if (marker != null) { - markerLabel.draw(new String[]{ + markerLabel.setText( + new String[]{ marker.name, String.format("(%d, %d, %d)", marker.x, marker.y, - marker.z)}, - null, - mouseX + 5, - mouseY, - true, - true, - this.width, - this.height - ); + marker.z) + }, + null + ); + markerLabel.setCoords(mouseX + 8, mouseY); + markerLabel.draw(); } // draw name of player under mouse cursor if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - markerLabel.draw(new String[]{ - this.mc.thePlayer.getDisplayNameString(), - String.format("(%d, %d, %d)", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt)}, - null, - mouseX + 5, - mouseY, - true, - true, - this.width, - this.height + markerLabel.setText( + new String[]{ + this.mc.thePlayer.getDisplayNameString(), + String.format("(%d, %d, %d)", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt) + }, + null ); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + markerLabel.setCoords(mouseX + 8, mouseY); + markerLabel.draw(); + } + } - // draw labels - this.helpLabel.draw(new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, null, menuX, menuY, true, false, this.width, this.height); - this.optionsLabel.drawToRightOf(this.helpLabel, new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, true, false, this.width, this.height); + private void drawLabel(int mouseX, int mouseY, float f) + { + this.helpLabel.draw(); + this.optionsLabel.draw(); String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, new String[]{dimString}, true, false, this.width, this.height); + this.dimensionLabel.setText(new String[]{dimString}, null); + this.dimensionLabel.draw(); + String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, new String[]{groupString}, true, false, this.width, this.height); + this.groupLabel.setText(new String[]{groupString}, null); + this.groupLabel.draw(); + String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, new String[]{overlayString}, true, false, this.width, this.height); - + this.overlayLabel.setText(new String[]{overlayString}, null); + this.overlayLabel.draw(); + if (!VersionCheck.isLatestVersion()) { - String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", - VersionCheck.getLatestVersion()); - this.updateLabel.drawToRightOf(this.overlayLabel, new String[]{updateString}, true, false, this.width, this.height); + + this.updateLabel.draw(); } // help message on mouse over if (this.helpLabel.posWithin(mouseX, mouseY)) { - helpTooltipLabel.draw(HelpText1,HelpText2, 10 , 20, true, false, this.width, this.height); + helpTooltipLabel.draw(); } if (this.updateLabel.posWithin(mouseX, mouseY)) { - updateTooltipLabel.draw(new String[]{VersionCheck.getUpdateURL()},null, 10 , 20, true, false, this.width, this.height); + updateTooltipLabel.draw(); } - - MarkerOverlay.drawScreen(mouseX, mouseY, f);; - - super.drawScreen(mouseX, mouseY, f); } - + public void confirmClicked(boolean result, int id) { if (id == 31102009) { if (result) { diff --git a/src/main/java/mapwriter/gui/MwGuiLabel.java b/src/main/java/mapwriter/gui/MwGuiLabel.java index 17b52589..41b09f51 100644 --- a/src/main/java/mapwriter/gui/MwGuiLabel.java +++ b/src/main/java/mapwriter/gui/MwGuiLabel.java @@ -11,64 +11,193 @@ public class MwGuiLabel static int spacingX = 4; static int spacingY = 2; private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; + private Boolean Background; + private Boolean AllowFlip; + private int parentWidth; + private int parentHeight; + private String str1; + private String str2; + private String[] s1; + private String[] s2; + private MwGuiLabel label; + private Side side = Side.none; - public MwGuiLabel() - { + private enum Side + { + left,right,top,bottom,none } - //TODO: remove all vars to own methods - public void draw(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { - this.x = x; - this.y = y; - - int stringwidth = Utils.getMaxWidth(s1, s2); - this.w = stringwidth < parentWidth - 20 ? stringwidth : parentWidth - 20; + + public MwGuiLabel(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) + { + this.Background = Background; + this.AllowFlip = AllowFlip; - String str = Utils.stringArrayToString(s1); - this.h = fontRendererObj.splitStringWidth(str, parentWidth); + this.parentWidth = parentWidth; + this.parentHeight = parentHeight; - if (AllowFlip) + this.setCoords(x, y); + this.setText(s1, s2); + } + + public void draw() + { + this.updateCoords(); + if (str1 != null) { - if (this.x + this.w + spacingX > parentWidth) + if(Background) { - this.x = this.x - this.w - spacingX - 5; + Gui.drawRect(this.x - spacingX, this.y - this.spacingY, this.x + this.w + this.spacingX, this.h + this.y + this.spacingY, 0x80000000); } - if (this.y + this.h + spacingY > parentHeight) + + this.fontRendererObj.drawSplitString(str1, this.x , this.y, this.w, 0xffffff); + + if (this.str2 != null) { - this.y = this.y - this.h - spacingY; + this.fontRendererObj.drawSplitString(str2, this.x + 65, this.y, this.w, 0xffffff); } } - - if(Background) - { - Gui.drawRect(this.x - spacingX, this.y - spacingY, this.x + this.w + spacingX, this.h + this.y + spacingY, 0x80000000); - } - - this.fontRendererObj.drawSplitString(str, this.x , this.y, this.w, 0xffffff); - - if (s2 != null) - { - this.fontRendererObj.drawSplitString(Utils.stringArrayToString(s2), this.x + 65, this.y, this.w, 0xffffff); - } } - public void drawToRightOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { - this.draw(s, null, label.x + label.w + (2 * spacingX) + 2, label.y, Background, AllowFlip, parentWidth, parentHeight); + public void drawToRightOf(MwGuiLabel label) + { + this.label = label; + this.side = Side.right; } - public void drawToLeftOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { - this.draw(s, null, label.x - label.w - (2 * spacingX) + 2, label.y, Background, AllowFlip, parentWidth, parentHeight); + public void drawToLeftOf(MwGuiLabel label) { + this.label = label; + this.side = Side.left; } - public void drawToBelowOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { - this.draw(s, null, label.x, label.y + label.h + (2 * spacingY) + 2, Background, AllowFlip, parentWidth, parentHeight); + public void drawToBelowOf(MwGuiLabel label) { + this.label = label; + this.side = Side.bottom; } - public void drawToAboveOf(MwGuiLabel label, String[] s, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) { - this.draw(s, null, label.x, label.y + label.h + (2 * spacingY) + 2, Background, AllowFlip, parentWidth, parentHeight); + public void drawToAboveOf(MwGuiLabel label) { + this.label = label; + this.side = Side.top; } + private void updateCoords() + { + switch (this.side) { + case left: + this.setCoords(this.label.x - (this.w + (2 * spacingX) + 2), this.label.y); + break; + + case right: + this.setCoords(this.label.x + this.label.w + (2 * spacingX) + 2, this.label.y); + break; + + case bottom: + this.setCoords(this.label.x, this.label.y + this.label.h + (2 * spacingY) + 2); + break; + + case top: + this.setCoords(this.label.x, this.label.y - (this.h + (2 * spacingY) + 2)); + break; + + default: + break; + } + } + public boolean posWithin(int x, int y) { return (x >= this.x + spacingX) && (y >= this.y + spacingY) && (x <= (this.x + this.w + spacingX)) && (y <= (this.y + this.h + spacingY)); } + + public void setDrawBackground(boolean enable) + { + Background = enable; + } + public boolean getDrawBackground() + { + return Background; + } + + public void setAllowFlip(boolean enable) + { + Background = enable; + } + public boolean getAllowFlip() + { + return Background; + } + + public int getparentWidth() + { + return parentWidth; + } + + public int getparentHeight() + { + return parentHeight; + } + + public void setCoords(int x, int y) + { + if (AllowFlip) + { + if (x + this.w + this.spacingX > this.parentWidth) + { + this.x = x - this.w - this.spacingX - 5; + } + else + { + this.x = x; + } + if (y + this.h + this.spacingY > this.parentHeight) + { + this.y = y - this.h - this.spacingY; + } + else + { + this.y = y; + } + } + else + { + this.x = x; + this.y = y; + } + } + + public void setParentWidthAndHeight(int width, int height) + { + this.parentWidth = width; + this.parentHeight = height; + + this.updateWidthAndHeight(); + } + + public void setText(String[] s1, String[] s2) + { + this.s1 = s1; + this.s2 = s2; + this.UpdateStrings(); + } + + private void UpdateStrings() + { + if (s1 != null && s1.length >0) + { + str1 = Utils.stringArrayToString(this.s1); + } + if (s2 != null && s2.length >0) + { + str2 = Utils.stringArrayToString(this.s2); + } + this.updateWidthAndHeight(); + } + private void updateWidthAndHeight() + { + if (s1 != null) + { + int stringwidth = Utils.getMaxWidth(s1, s2); + this.w = stringwidth < parentWidth - 20 ? stringwidth : parentWidth - 20; + this.h = fontRendererObj.splitStringWidth(str1, parentWidth > 0 ? parentWidth : 10); + } + } } diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java index 83528863..60177117 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -99,9 +99,9 @@ protected void drawBackground() @Override protected void drawSlot(int entryID, int x, int y, int slotHeight, int mouseXIn, int mouseYIn) { - MwGuiLabel label = new MwGuiLabel(); + MwGuiLabel label = new MwGuiLabel(getLabelString(entryID), null, x, y, false, false, this.listWidth, this.height); - label.draw(getLabelString(entryID), null, x, y, false, false, this.listWidth, this.height); + label.draw(); } @Override From 414efe067cdee59a960b0b0112d11f88f2149110 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 12 Sep 2015 14:32:47 +0200 Subject: [PATCH 072/109] added curse project id --- build.properties | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/build.properties b/build.properties index f98dd34e..d90299b0 100644 --- a/build.properties +++ b/build.properties @@ -1,6 +1,7 @@ -mod_name=MapWriter -mod_group=vectron -mc_version=1.8 -forge_version=11.14.3.1450 -mcp_version=snapshot_20150615 -mod_version=2.2.8 +mod_name=MapWriter +mod_group=vectron +mc_version=1.8 +forge_version=11.14.3.1450 +mcp_version=snapshot_20150615 +mod_version=2.2.8 +curse_project_id=231387 \ No newline at end of file From c4422fd419fe4598079a1c3f09409963868c1d5b Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 12 Sep 2015 15:09:13 +0200 Subject: [PATCH 073/109] foult left from the merge --- build.properties | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/build.properties b/build.properties index d2557dff..a0e93488 100644 --- a/build.properties +++ b/build.properties @@ -1,16 +1,7 @@ -<<<<<<< HEAD mod_name=MapWriter mod_group=vectron mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 -mod_version=2.2.8 -======= -mod_name=MapWriter -mod_group=vectron -mc_version=1.7.10 -forge_version=10.13.4.1448-1.7.10 -mcp_version=stable_nodoc_12 -mod_version=2.1.9 ->>>>>>> refs/remotes/origin/master +mod_version=2.2.8 curse_project_id=231387 \ No newline at end of file From 95955c75719310d5435143feb12dc033cc874fb0 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 12 Sep 2015 18:21:31 +0200 Subject: [PATCH 074/109] 1.8 update --- src/main/java/mapwriter/BlockColourGen.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index ffa00bfa..d668d735 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -9,6 +9,7 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.ColorizerGrass; import net.minecraft.world.biome.BiomeGenBase; @@ -145,7 +146,7 @@ public static void genBlockColours(BlockColours bc) { blockColour = getIconMapColour(icon, terrainTexture); //request icon with meta 16, carpenterblocks uses this method to get the real texture //this makes the carpenterblocks render as brown blocks on the map - if (((String) Block.blockRegistry.getNameForObject(block)).contains("CarpentersBlocks")) + if (((ResourceLocation)Block.blockRegistry.getNameForObject(block)).getResourceDomain().contains("CarpentersBlocks")) { //icon = block.getIcon(1, 16); //blockColour = getIconMapColour(icon, terrainTexture); From 0321633e423f31fc9a840c3e5005a9c0a79a2ac1 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 12 Sep 2015 23:54:49 +0200 Subject: [PATCH 075/109] added a color selector to the new marker dialog. moved the color selector code out of the marker class remade the scrollable controlls moved the beta for the next update --- build.properties | 2 +- .../java/mapwriter/gui/MwGuiMarkerDialog.java | 3 +- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 250 ++++++++++---- .../gui/ScrollableColorSelector.java | 241 ++++++++++++++ .../java/mapwriter/gui/ScrollableField.java | 122 +++++++ .../java/mapwriter/gui/ScrollableTextBox.java | 313 +++++++++--------- src/main/java/mapwriter/map/Marker.java | 23 +- .../java/mapwriter/map/MarkerManager.java | 8 +- src/main/java/mapwriter/util/Utils.java | 26 +- .../assets/mapwriter/lang/en_US.lang | 8 +- 10 files changed, 754 insertions(+), 242 deletions(-) create mode 100644 src/main/java/mapwriter/gui/ScrollableColorSelector.java create mode 100644 src/main/java/mapwriter/gui/ScrollableField.java diff --git a/build.properties b/build.properties index a0e93488..f09e73bf 100644 --- a/build.properties +++ b/build.properties @@ -3,5 +3,5 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 -mod_version=2.2.8 +mod_version=2.2.9-Beta curse_project_id=231387 \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java index 24e00fd8..65b67ec6 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -2,6 +2,7 @@ import mapwriter.map.Marker; import mapwriter.map.MarkerManager; +import mapwriter.util.Utils; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.relauncher.Side; @@ -93,7 +94,7 @@ public boolean submit() { this.markerZ = this.getInputAsInt(); if (this.inputValid) { done = true; - int colour = Marker.getCurrentColour(); + int colour = Utils.getCurrentColour(); if (this.editingMarker != null) { colour = this.editingMarker.colour; this.markerManager.delMarker(this.editingMarker); diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index 9c0671da..796e6536 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -2,11 +2,12 @@ import java.io.IOException; +import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.map.Marker; import mapwriter.map.MarkerManager; +import mapwriter.util.Utils; import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.relauncher.Side; @@ -24,14 +25,17 @@ public class MwGuiMarkerDialogNew extends GuiScreen { private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; + private String editMarkerColor = "mw.gui.mwguimarkerdialognew.editMarkerColor"; ScrollableTextBox scrollableTextBoxName = null; ScrollableTextBox scrollableTextBoxGroup = null; ScrollableNumericTextBox scrollableNumericTextBoxX = null; ScrollableNumericTextBox scrollableNumericTextBoxY = null; ScrollableNumericTextBox scrollableNumericTextBoxZ = null; + ScrollableColorSelector ScrollableColorSelectorColor = null; boolean backToGameOnSubmit = false; static final int dialogWidthPercent = 40; static final int elementVSpacing = 20; + static final int numberOfElements = 8; private final MarkerManager markerManager; private Marker editingMarker; private String markerName = ""; @@ -40,25 +44,39 @@ public class MwGuiMarkerDialogNew extends GuiScreen { private int markerY = 80; private int markerZ = 0; private int dimension = 0; + private int colour = 0; - public MwGuiMarkerDialogNew(GuiScreen parentScreen, - MarkerManager markerManager, String markerName, String markerGroup, - int x, int y, int z, int dimension) { + public MwGuiMarkerDialogNew( + GuiScreen parentScreen, + MarkerManager markerManager, + String markerName, + String markerGroup, + int x, + int y, + int z, + int dimension + ) + { this.markerManager = markerManager; this.markerName = markerName; this.markerGroup = markerGroup; this.markerX = x; this.markerY = y; this.markerZ = z; - this.editingMarker = null; this.dimension = dimension; + this.colour = Utils.getCurrentColour(); + this.editingMarker = null; this.parentScreen = parentScreen; this.title = this.titleNew; } - public MwGuiMarkerDialogNew(GuiScreen parentScreen, - MarkerManager markerManager, Marker editingMarker) { + public MwGuiMarkerDialogNew( + GuiScreen parentScreen, + MarkerManager markerManager, + Marker editingMarker + ) + { this.markerManager = markerManager; this.editingMarker = editingMarker; this.markerName = editingMarker.name; @@ -67,42 +85,84 @@ public MwGuiMarkerDialogNew(GuiScreen parentScreen, this.markerY = editingMarker.y; this.markerZ = editingMarker.z; this.dimension = editingMarker.dimension; + this.colour = editingMarker.colour; this.parentScreen = parentScreen; this.title = this.titleEdit; } public boolean submit() { boolean inputCorrect = true; + if (scrollableTextBoxName.validateTextFieldData()) + { this.markerName = scrollableTextBoxName.getText(); + } else + { inputCorrect = false; + } + if (scrollableTextBoxGroup.validateTextFieldData()) + { this.markerGroup = scrollableTextBoxGroup.getText(); + } else + { inputCorrect = false; + } + if (scrollableNumericTextBoxX.validateTextFieldData()) + { this.markerX = scrollableNumericTextBoxX.getTextFieldIntValue(); + } else + { inputCorrect = false; + } + if (scrollableNumericTextBoxY.validateTextFieldData()) + { this.markerY = scrollableNumericTextBoxY.getTextFieldIntValue(); + } else + { inputCorrect = false; + } + if (scrollableNumericTextBoxZ.validateTextFieldData()) + { this.markerZ = scrollableNumericTextBoxZ.getTextFieldIntValue(); + } else + { inputCorrect = false; - if (inputCorrect) { - int colour = Marker.getCurrentColour(); - if (this.editingMarker != null) { - colour = this.editingMarker.colour; + } + + if (ScrollableColorSelectorColor.validateColorData()) + { + this.colour = ScrollableColorSelectorColor.getColor(); + } + else + { + inputCorrect = false; + } + + if (inputCorrect) + { + if (this.editingMarker != null) + { this.markerManager.delMarker(this.editingMarker); this.editingMarker = null; } - this.markerManager.addMarker(this.markerName, this.markerGroup, - this.markerX, this.markerY, this.markerZ, this.dimension, - colour); + this.markerManager.addMarker( + this.markerName, + this.markerGroup, + this.markerX, + this.markerY, + this.markerZ, + this.dimension, + this.colour + ); this.markerManager.setVisibleGroupName(this.markerGroup); this.markerManager.update(); } @@ -111,56 +171,93 @@ public boolean submit() { public void initGui() { int labelsWidth = this.fontRendererObj.getStringWidth("Group"); - int width = this.width * dialogWidthPercent / 100 - labelsWidth; - int x = (this.width - width) / 2 + labelsWidth; - int y = (this.height - elementVSpacing * 5) / 2; + int width = (this.width * dialogWidthPercent / 100) - labelsWidth - 20; + int x = (this.width - width + labelsWidth) / 2; + int y = (this.height - elementVSpacing * numberOfElements) / 2; - this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); + this.scrollableTextBoxName = new ScrollableTextBox( + x, + y, + width, + I18n.format(this.editMarkerName, new Object[0]), + this.fontRendererObj + ); this.scrollableTextBoxName.setFocused(true); this.scrollableTextBoxName.setText(this.markerName); - this.scrollableTextBoxGroup = new ScrollableTextBox(x, y - + MwGuiMarkerDialogNew.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), - this.markerManager.groupList, this.fontRendererObj); + this.scrollableTextBoxGroup = new ScrollableTextBox( + x, + y + MwGuiMarkerDialogNew.elementVSpacing, + width, + I18n.format(this.editMarkerGroup, new Object[0]), + this.markerManager.groupList, + this.fontRendererObj + ); this.scrollableTextBoxGroup.setText(this.markerGroup); this.scrollableTextBoxGroup.setDrawArrows(true); - this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y - + MwGuiMarkerDialogNew.elementVSpacing * 2, width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxX = new ScrollableNumericTextBox( + x, + y + MwGuiMarkerDialogNew.elementVSpacing * 2, + width, + I18n.format(this.editMarkerX, new Object[0]), + this.fontRendererObj + ); this.scrollableNumericTextBoxX.setText("" + this.markerX); this.scrollableNumericTextBoxX.setDrawArrows(true); - this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y - + MwGuiMarkerDialogNew.elementVSpacing * 3, width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxY = new ScrollableNumericTextBox( + x, + y + MwGuiMarkerDialogNew.elementVSpacing * 3, + width, + I18n.format(this.editMarkerY, new Object[0]), + this.fontRendererObj + ); this.scrollableNumericTextBoxY.setText("" + this.markerY); this.scrollableNumericTextBoxY.setDrawArrows(true); - this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y - + MwGuiMarkerDialogNew.elementVSpacing * 4, width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox( + x, + y + MwGuiMarkerDialogNew.elementVSpacing * 4, + width, + I18n.format(this.editMarkerZ, new Object[0]), + this.fontRendererObj + ); this.scrollableNumericTextBoxZ.setText("" + this.markerZ); this.scrollableNumericTextBoxZ.setDrawArrows(true); + + this.ScrollableColorSelectorColor = new ScrollableColorSelector( + x, + y + MwGuiMarkerDialogNew.elementVSpacing * 5, + width, + I18n.format(this.editMarkerColor, new Object[0]), + this.fontRendererObj + ); + this.ScrollableColorSelectorColor.setColor(this.colour); + this.ScrollableColorSelectorColor.setDrawArrows(true); } + @Override public void drawScreen(int mouseX, int mouseY, float f) { if (this.parentScreen != null) { this.parentScreen.drawScreen(mouseX, mouseY, f); } else { this.drawDefaultBackground(); } + int w = this.width * MwGuiMarkerDialogNew.dialogWidthPercent / 100; - //int y = (this.height - MwGuiMarkerDialogNew.elementVSpacing * 5) / 2 + 2; drawRect( (this.width - w) / 2, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * 7) / 2 - 4, + (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2)) / 2 - 4, (this.width - w) / 2 + w, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * 7) / 2 - + MwGuiMarkerDialogNew.elementVSpacing * 6, + (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2)) / 2 + + MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1), 0x80000000); this.drawCenteredString( this.fontRendererObj, I18n.format(this.title, new Object[0]), (this.width) / 2, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * 6) / 2 + (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1)) / 2 - MwGuiMarkerDialogNew.elementVSpacing / 4, 0xffffff); this.scrollableTextBoxName.draw(); @@ -168,6 +265,7 @@ public void drawScreen(int mouseX, int mouseY, float f) { this.scrollableNumericTextBoxX.draw(); this.scrollableNumericTextBoxY.draw(); this.scrollableNumericTextBoxZ.draw(); + this.ScrollableColorSelectorColor.draw(); super.drawScreen(mouseX, mouseY, f); } @@ -193,15 +291,18 @@ public void mouseDWheelScrolled(int x, int y, int direction) { this.scrollableNumericTextBoxX.mouseDWheelScrolled(x, y, direction); this.scrollableNumericTextBoxY.mouseDWheelScrolled(x, y, direction); this.scrollableNumericTextBoxZ.mouseDWheelScrolled(x, y, direction); + this.ScrollableColorSelectorColor.mouseDWheelScrolled(x, y, direction); } protected void mouseClicked(int x, int y, int button) throws IOException { super.mouseClicked(x, y, button); - this.scrollableTextBoxName.mouseClicked(x, y, button); - this.scrollableTextBoxGroup.mouseClicked(x, y, button); - this.scrollableNumericTextBoxX.mouseClicked(x, y, button); - this.scrollableNumericTextBoxY.mouseClicked(x, y, button); - this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); + + this.scrollableTextBoxName.mouseClicked(x, y, button); + this.scrollableTextBoxGroup.mouseClicked(x, y, button); + this.scrollableNumericTextBoxX.mouseClicked(x, y, button); + this.scrollableNumericTextBoxY.mouseClicked(x, y, button); + this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); + this.ScrollableColorSelectorColor.mouseClicked(x, y, button); } protected void keyTyped(char c, int key) { @@ -211,7 +312,8 @@ protected void keyTyped(char c, int key) { break; case Keyboard.KEY_RETURN: // when enter pressed, submit current input - if (this.submit()) { + if (this.submit()) + { if (!this.backToGameOnSubmit) { this.mc.displayGuiScreen(this.parentScreen); } else { @@ -220,66 +322,70 @@ protected void keyTyped(char c, int key) { } break; case Keyboard.KEY_TAB: - GuiTextField thistextField = null; - GuiTextField prevtextField = null; - GuiTextField nexttextField = null; + ScrollableField thisField = null; + ScrollableField prevField = null; + ScrollableField nextField = null; if (this.scrollableTextBoxName.isFocused()) { - thistextField = scrollableTextBoxName; - prevtextField = scrollableNumericTextBoxZ; - nexttextField = scrollableTextBoxGroup; + thisField = scrollableTextBoxName; + prevField = ScrollableColorSelectorColor; + nextField = scrollableTextBoxGroup; } else if (this.scrollableTextBoxGroup.isFocused()) { - thistextField = scrollableTextBoxGroup; - prevtextField = scrollableTextBoxName; - nexttextField = scrollableNumericTextBoxX; + thisField = scrollableTextBoxGroup; + prevField = scrollableTextBoxName; + nextField = scrollableNumericTextBoxX; } else if (this.scrollableNumericTextBoxX.isFocused()) { - thistextField = scrollableNumericTextBoxX; - prevtextField = scrollableTextBoxGroup; - nexttextField = scrollableNumericTextBoxY; + thisField = scrollableNumericTextBoxX; + prevField = scrollableTextBoxGroup; + nextField = scrollableNumericTextBoxY; } else if (this.scrollableNumericTextBoxY.isFocused()) { - thistextField = scrollableNumericTextBoxY; - prevtextField = scrollableNumericTextBoxX; - nexttextField = scrollableNumericTextBoxZ; + thisField = scrollableNumericTextBoxY; + prevField = scrollableNumericTextBoxX; + nextField = scrollableNumericTextBoxZ; } else if (this.scrollableNumericTextBoxZ.isFocused()) { - thistextField = scrollableNumericTextBoxZ; - prevtextField = scrollableNumericTextBoxY; - nexttextField = scrollableTextBoxName; + thisField = scrollableNumericTextBoxZ; + prevField = scrollableNumericTextBoxY; + nextField = ScrollableColorSelectorColor; } + else if (this.ScrollableColorSelectorColor.isFocused()) + { + thisField = this.ScrollableColorSelectorColor.thisField(); + nextField = this.ScrollableColorSelectorColor.nextField(scrollableTextBoxName); + prevField = this.ScrollableColorSelectorColor.prevField((ScrollableField)scrollableNumericTextBoxZ); + } + + thisField.setFocused(false); - thistextField.setFocused(false); - thistextField.setCursorPositionEnd(); + if (thisField instanceof ScrollableTextBox) + { + ((ScrollableTextBox)thisField).setCursorPositionEnd(); + } if (Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)) { - prevtextField.setFocused(true); - prevtextField.setSelectionPos(0); + prevField.setFocused(true); } else { - nexttextField.setFocused(true); - nexttextField.setSelectionPos(0); + nextField.setFocused(true); } break; default: - if (this.scrollableTextBoxName.isFocused()) - this.scrollableTextBoxName.textboxKeyTyped(c, key); - else if (this.scrollableTextBoxGroup.isFocused()) - this.scrollableTextBoxGroup.textboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxX.isFocused()) - this.scrollableNumericTextBoxX.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxY.isFocused()) - this.scrollableNumericTextBoxY.validateTextboxKeyTyped(c, key); - else if (this.scrollableNumericTextBoxZ.isFocused()) - this.scrollableNumericTextBoxZ.validateTextboxKeyTyped(c, key); + this.scrollableTextBoxName.KeyTyped(c, key); + this.scrollableTextBoxGroup.KeyTyped(c, key); + this.scrollableNumericTextBoxX.KeyTyped(c, key); + this.scrollableNumericTextBoxY.KeyTyped(c, key); + this.scrollableNumericTextBoxZ.KeyTyped(c, key); + this.ScrollableColorSelectorColor.KeyTyped(c, key); break; } } diff --git a/src/main/java/mapwriter/gui/ScrollableColorSelector.java b/src/main/java/mapwriter/gui/ScrollableColorSelector.java new file mode 100644 index 00000000..5828f140 --- /dev/null +++ b/src/main/java/mapwriter/gui/ScrollableColorSelector.java @@ -0,0 +1,241 @@ +package mapwriter.gui; + +import java.util.List; + +import org.lwjgl.input.Keyboard; + +import mapwriter.util.Utils; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.resources.I18n; + +public class ScrollableColorSelector extends ScrollableField +{ + private String editRed = "mw.gui.ScrollableColorSelector.Red"; + private String editGreen = "mw.gui.ScrollableColorSelector.Green"; + private String editBlue = "mw.gui.ScrollableColorSelector.Blue"; + + private ScrollableNumericTextBox ScrollableNumericTextBoxColourRed; + private ScrollableNumericTextBox ScrollableNumericTextBoxColourGreen; + private ScrollableNumericTextBox ScrollableNumericTextBoxColourBlue; + + private int colour = 0; + + private int colourFieldX = 0; + private int colourFieldY = 0; + private int colourFieldW = 0; + private int colourFieldH = 0; + + private int y; + + public ScrollableColorSelector( + int x, + int y, + int width, + String label, + FontRenderer fontrendererObj + ) + { + super(x, y + MwGuiMarkerDialogNew.elementVSpacing, width, label, fontrendererObj); + this.y = y; + this.init(); + } + + private void init() + { + int textboxWidth = 16; + int x1 = this.x + ScrollableField.arrowsWidth + this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) + 4; + int w = (ScrollableField.arrowsWidth * 2) + + this.fontrendererObj.getStringWidth("999") + + textboxWidth; + + ScrollableNumericTextBoxColourRed = new ScrollableNumericTextBox( + x1, + this.y, + w, + I18n.format(this.editRed, new Object[0]), + this.fontrendererObj + ); + ScrollableNumericTextBoxColourRed.setDrawArrows(true); + ScrollableNumericTextBoxColourRed.setMaxValue(255); + ScrollableNumericTextBoxColourRed.setMinValue(0); + + ScrollableNumericTextBoxColourGreen = new ScrollableNumericTextBox( + x1, + this.y + MwGuiMarkerDialogNew.elementVSpacing, + w, + I18n.format(this.editGreen, new Object[0]), + this.fontrendererObj + ); + ScrollableNumericTextBoxColourGreen.setDrawArrows(true); + ScrollableNumericTextBoxColourGreen.setMaxValue(255); + ScrollableNumericTextBoxColourGreen.setMinValue(0); + + ScrollableNumericTextBoxColourBlue = new ScrollableNumericTextBox( + x1, + this.y + MwGuiMarkerDialogNew.elementVSpacing * 2, + w, + I18n.format(this.editBlue, new Object[0]), + this.fontrendererObj + ); + ScrollableNumericTextBoxColourBlue.setDrawArrows(true); + ScrollableNumericTextBoxColourBlue.setMaxValue(255); + ScrollableNumericTextBoxColourBlue.setMinValue(0); + + colourFieldX = x1 + w + 2; + colourFieldY = this.y + 6; + colourFieldW = this.width - + w - + (ScrollableField.arrowsWidth * 2) - + this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) - + 8; + colourFieldH = MwGuiMarkerDialogNew.elementVSpacing * 2; + } + + @Override + public void nextElement() + { + setColor(Utils.getNextColour()); + } + + @Override + public void previousElement() + { + setColor(Utils.getPrevColour()); + } + + @Override + public void setFocused(Boolean focus) + { + this.ScrollableNumericTextBoxColourRed.setFocused(focus); + } + + @Override + public Boolean isFocused() + { + if ( + this.ScrollableNumericTextBoxColourRed.isFocused() || + this.ScrollableNumericTextBoxColourGreen.isFocused() || + this.ScrollableNumericTextBoxColourBlue.isFocused() + ) + { + return true; + } + return false; + } + + public boolean validateColorData() + { + return ( + (this.ScrollableNumericTextBoxColourRed.getText().length() > 0) && + (this.ScrollableNumericTextBoxColourGreen.getText().length() > 0) && + (this.ScrollableNumericTextBoxColourBlue.getText().length() > 0) + ); + } + + public int getColor() + { + return this.colour; + } + + public void setColor(int colour) + { + this.colour = colour; + + int red = (colour >> 16) & 0xff; + int green = (colour >> 8) & 0xff; + int blue = (colour) & 0xff; + int alpha = (colour >> 24) & 0xff; + + ScrollableNumericTextBoxColourRed.setText(red); + ScrollableNumericTextBoxColourGreen.setText(green); + ScrollableNumericTextBoxColourBlue.setText(blue); + } + + private void UpdateColour() + { + int colour = 0xff << 24; + colour += this.ScrollableNumericTextBoxColourRed.getTextFieldIntValue() << 16; + colour += this.ScrollableNumericTextBoxColourGreen.getTextFieldIntValue() << 8; + colour += this.ScrollableNumericTextBoxColourBlue.getTextFieldIntValue(); + this.colour = colour; + } + + @Override + public void mouseClicked(int x, int y, int button) + { + super.mouseClicked(x, y, button); + this.ScrollableNumericTextBoxColourRed.mouseClicked(x, y, button); + this.ScrollableNumericTextBoxColourGreen.mouseClicked(x, y, button); + this.ScrollableNumericTextBoxColourBlue.mouseClicked(x, y, button); + } + + public void mouseDWheelScrolled(int x, int y, int direction) + { + // TODO Auto-generated method stub + } + + public void KeyTyped(char c, int key) + { + this.ScrollableNumericTextBoxColourRed.KeyTyped(c, key); + this.ScrollableNumericTextBoxColourGreen.KeyTyped(c, key); + this.ScrollableNumericTextBoxColourBlue.KeyTyped(c, key); + } + + @Override + public void draw() + { + super.draw(); + this.ScrollableNumericTextBoxColourRed.draw(); + this.ScrollableNumericTextBoxColourGreen.draw(); + this.ScrollableNumericTextBoxColourBlue.draw(); + + UpdateColour(); + + this.drawRect(colourFieldX -1, colourFieldY-1, colourFieldX + colourFieldW + 1, colourFieldY + colourFieldH + 1, 0xff000000); + this.drawRect(colourFieldX, colourFieldY, colourFieldX + colourFieldW, colourFieldY + colourFieldH, this.colour); + } + + public ScrollableField thisField() + { + if (this.ScrollableNumericTextBoxColourRed.isFocused()) + { + return this.ScrollableNumericTextBoxColourRed; + } + if (this.ScrollableNumericTextBoxColourGreen.isFocused()) + { + return this.ScrollableNumericTextBoxColourGreen; + } + if (this.ScrollableNumericTextBoxColourBlue.isFocused()) + { + return this.ScrollableNumericTextBoxColourBlue; + } + return this.ScrollableNumericTextBoxColourRed; + } + + public ScrollableField nextField(ScrollableField field) + { + if (this.ScrollableNumericTextBoxColourRed.isFocused()) + { + return this.ScrollableNumericTextBoxColourGreen; + } + if (this.ScrollableNumericTextBoxColourGreen.isFocused()) + { + return this.ScrollableNumericTextBoxColourBlue; + } + return field; + } + + public ScrollableField prevField(ScrollableField field) + { + if (this.ScrollableNumericTextBoxColourGreen.isFocused()) + { + return this.ScrollableNumericTextBoxColourRed; + } + if (this.ScrollableNumericTextBoxColourBlue.isFocused()) + { + return this.ScrollableNumericTextBoxColourGreen; + } + return field; + } +} diff --git a/src/main/java/mapwriter/gui/ScrollableField.java b/src/main/java/mapwriter/gui/ScrollableField.java new file mode 100644 index 00000000..3da6388a --- /dev/null +++ b/src/main/java/mapwriter/gui/ScrollableField.java @@ -0,0 +1,122 @@ +package mapwriter.gui; + +import mapwriter.util.Reference; +import mapwriter.util.Render; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.texture.TextureManager; + +public abstract class ScrollableField extends Gui +{ + public int x; + public int y; + public int width; + + public int labelX; + public int labelY; + public int labelWidth; + public int labelHeight; + public String label; + + private boolean drawArrows = false; + private int leftArrowX; + private int rightArrowX; + private int arrowsY; + public static int arrowsWidth = 7; + private int arrowsHeight = 12; + + public final FontRenderer fontrendererObj; + + public ScrollableField(int x, int y, int width, String label, FontRenderer fontrendererObj) + { + this.x = x; + this.y = y; + this.width = width; + + this.fontrendererObj = fontrendererObj; + this.label = label; + + this.leftArrowX = this.x + 1; + this.rightArrowX = this.x + (this.width - ScrollableField.arrowsWidth); + this.arrowsY = this.y; + + this.labelWidth = fontrendererObj.getStringWidth(this.label); + this.labelHeight = this.fontrendererObj.FONT_HEIGHT; + this.labelX = this.x - this.labelWidth; + this.labelY = this.y + this.labelHeight / 2 - 2; + } + + public void draw() + { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + //Render.drawRectBorder(labelX, y, width + this.labelWidth + 4, this.arrowsHeight, 2); + + //draw the description label + drawString(this.fontrendererObj, this.label, this.labelX, this.labelY, 0xffffff); + + if (this.drawArrows) + { + renderEngine.bindTexture(Reference.leftArrowTexture); + Render.drawTexturedRect( + this.leftArrowX, + this.arrowsY, + ScrollableField.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + renderEngine.bindTexture(Reference.rightArrowTexture); + Render.drawTexturedRect( + this.rightArrowX, + this.arrowsY, + ScrollableField.arrowsWidth, + this.arrowsHeight, + 0.0, + 0.0, + 1.0, + 1.0 + ); + } + } + + public void setDrawArrows(boolean value) { + this.drawArrows = value; + } + + public void mouseClicked(int x, int y, int button) { + int direction = this.posWithinArrows(x, y); + if (direction == 1) + { + this.nextElement(); + } + else if(direction == -1) + { + this.previousElement(); + } + } + + /** + * + * @return Returns clicked arrow: 1 for right and -1 for left + */ + public int posWithinArrows(int x, int y) { + if ((x >= this.leftArrowX) && (y >= this.arrowsY) + && (x <= ScrollableField.arrowsWidth + this.leftArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return -1; + else if ((x >= this.rightArrowX) && (y >= this.arrowsY) + && (x <= ScrollableField.arrowsWidth + this.rightArrowX) + && (y <= this.arrowsHeight + this.arrowsY)) + return 1; + else + return 0; + } + + public abstract void nextElement(); + public abstract void previousElement(); + public abstract void setFocused(Boolean focus); + public abstract Boolean isFocused(); +} diff --git a/src/main/java/mapwriter/gui/ScrollableTextBox.java b/src/main/java/mapwriter/gui/ScrollableTextBox.java index 4f28b1eb..2238ebdf 100644 --- a/src/main/java/mapwriter/gui/ScrollableTextBox.java +++ b/src/main/java/mapwriter/gui/ScrollableTextBox.java @@ -11,169 +11,85 @@ import org.lwjgl.input.Keyboard; -public class ScrollableTextBox extends GuiTextField - { - public int x; - public int y; - public int width; - // private int height; - public int labelX; - public int labelY; - public int labelWidth; - public int labelHeight; - public String label; - public boolean drawArrows = false; - public int leftArrowX; - public int rightArrowX; - public int arrowsY; - public static int arrowsWidth = 7; - public int arrowsHeight = 12; +public class ScrollableTextBox extends ScrollableField + { public int textFieldX; public int textFieldY; public int textFieldWidth; - public static int textFieldHeight = 12; + private static int textFieldHeight = 12; + public List scrollableElements; - private final FontRenderer fontRendererInstance; + + protected GuiTextField textField; ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) - { - super( - 0, - fontrendererObj, - x + arrowsWidth, - y, - width - arrowsWidth * 2 - 25, - textFieldHeight - ); - - this.x = x; - this.y = y; - this.width = width; - this.label = label; - this.fontRendererInstance = fontrendererObj; - + { + super(x, y, width, label, fontrendererObj); this.init(); } ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) - { - super( - 0, - fontrendererObj, - x + arrowsWidth, - y, - width - arrowsWidth * 2 - 25, - textFieldHeight - ); - - this.x = x; - this.y = y; - this.width = width; - this.label = label; + { + super(x, y, width, label, fontrendererObj); this.scrollableElements = scrollableElements; - this.fontRendererInstance = fontrendererObj; this.init(); } - private void init() { - setMaxStringLength(32); - this.textFieldX = x + arrowsWidth; + private void init() + { + this.textFieldX = this.x + this.arrowsWidth + 3; this.textFieldY = this.y; - this.textFieldWidth = width - arrowsWidth * 2 - 25; - this.labelWidth = fontRendererInstance - .getStringWidth(this.label); - this.labelHeight = this.fontRendererInstance.FONT_HEIGHT; - this.labelX = this.x - this.labelWidth - 4; - this.labelY = this.y + this.labelHeight / 2 - 2; - this.leftArrowX = this.x - 1; - this.rightArrowX = this.textFieldX + this.textFieldWidth + 1; - this.arrowsY = this.y; - } - - public void draw() { - drawString(this.fontRendererInstance, this.label, this.labelX, this.labelY, 0xffffff); - if (this.drawArrows) + this.textFieldWidth = this.width - 5 - ScrollableField.arrowsWidth * 2; + + textField = new GuiTextField( + 0, + this.fontrendererObj, + this.textFieldX, + this.textFieldY, + this.textFieldWidth, + this.textFieldHeight + ); + + textField.setMaxStringLength(32); + + } + + @Override + public void draw() + { + super.draw(); + this.textField.drawTextBox(); + if (!this.validateTextFieldData()) { - TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; - renderEngine.bindTexture(Reference.leftArrowTexture); - Render.drawTexturedRect( - this.leftArrowX, - this.arrowsY, - ScrollableTextBox.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); - renderEngine.bindTexture(Reference.rightArrowTexture); - Render.drawTexturedRect( - this.rightArrowX, - this.arrowsY, - ScrollableTextBox.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); - } - drawTextBox(); - if (!this.validateTextFieldData()) { - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX + this.textFieldWidth + 1, - this.textFieldY, - 0xff900000); - drawRect(this.textFieldX - 1, this.textFieldY - 1, - this.textFieldX, this.textFieldY + ScrollableTextBox.textFieldHeight + 1, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + ScrollableTextBox.textFieldHeight + 1, - this.textFieldX, - this.textFieldY + ScrollableTextBox.textFieldHeight, - 0xff900000); - drawRect(this.textFieldX + this.textFieldWidth + 1, - this.textFieldY + ScrollableTextBox.textFieldHeight + 1, - this.textFieldX + this.textFieldWidth, this.textFieldY, - 0xff900000); + //draw a red rectangle over the textbox to indicate that the text is invallid + int x1 = this.textFieldX - 1; + int y1 = this.textFieldY - 1; + int x2 = this.textFieldX + this.textFieldWidth; + int y2 = this.textFieldY + ScrollableTextBox.textFieldHeight; + int colour = 0xff900000; + + this.drawHorizontalLine(x1, x2, y1, colour); + this.drawHorizontalLine(x1, x2, y2, colour); + + this.drawVerticalLine(x1, y1, y2, colour); + this.drawVerticalLine(x2, y1, y2, colour); } } - public void mouseClicked(int x, int y, int button) { - int direction = this.posWithinArrows(x, y); - if (direction != 0) - this.textFieldScroll(direction); + @Override + public void mouseClicked(int x, int y, int button) + { super.mouseClicked(x, y, button); + this.textField.mouseClicked(x, y, button); } - - public void setDrawArrows(boolean value) { - this.drawArrows = value; - } - + public void mouseDWheelScrolled(int x, int y, int direction) { if (posWithinTextField(x, y)) textFieldScroll(-direction); } public boolean validateTextFieldData() { - return getText().length() > 0; - } - - /** - * - * @return Returns clicked arrow: 1 for right and -1 for left - */ - public int posWithinArrows(int x, int y) { - if ((x >= this.leftArrowX) && (y >= this.arrowsY) - && (x <= ScrollableTextBox.arrowsWidth + this.leftArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return -1; - else if ((x >= this.rightArrowX) && (y >= this.arrowsY) - && (x <= ScrollableTextBox.arrowsWidth + this.rightArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) - return 1; - else - return 0; + return this.getText().length() > 0; } public boolean posWithinTextField(int x, int y) { @@ -184,7 +100,7 @@ public boolean posWithinTextField(int x, int y) { public void textFieldScroll(int direction) { if (this.scrollableElements != null) { - int index = this.scrollableElements.indexOf(getText().trim()); + int index = this.scrollableElements.indexOf( this.getText().trim()); if (direction > 0) { if (index == -1 || index == this.scrollableElements.size() - 1) @@ -197,37 +113,138 @@ public void textFieldScroll(int direction) { else index--; } - setText(this.scrollableElements.get(index)); + this.textField.setText(this.scrollableElements.get(index)); } } + + @Override + public void nextElement() + { + this.textFieldScroll(1); + } + + @Override + public void previousElement() + { + this.textFieldScroll(-1); + } + + public String getText() + { + return this.textField.getText(); + } + + public void setText(String text) + { + this.textField.setText(text); + } + + public void setFocused(Boolean focus) + { + this.textField.setFocused(focus); + this.textField.setSelectionPos(0); + } + + public Boolean isFocused() + { + return this.textField.isFocused(); + } + + public void KeyTyped(char c, int key) + { + this.textField.textboxKeyTyped(c, key); + } + + public int getCursorPosition() + { + return this.textField.getCursorPosition(); + } + + public void setCursorPositionEnd() + { + this.textField.setCursorPositionEnd(); + } } class ScrollableNumericTextBox extends ScrollableTextBox { + public int maxValue = -1; + public int minValue = -1; + public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) { super(x, y, width, label, fontrendererObj); } @Override - public void textFieldScroll(int direction) { - if (this.validateTextFieldData()) { - int value = this.getTextFieldIntValue(); + public void textFieldScroll(int direction) + { + int newValue = 0; + if (this.validateTextFieldData()) + { + newValue = this.getTextFieldIntValue(); if (direction > 0) - setText("" + (value + 1)); + { + if(this.maxValue < 0 || newValue + 1 <= this.maxValue) + { + newValue += 1; + } + } else if (direction < 0) - setText("" + (value - 1)); + { + if(this.minValue < 0 || newValue - 1 >= this.minValue) + { + newValue -= 1; + } + } } + this.setText(newValue); } - public int getTextFieldIntValue() { - return Integer.parseInt(getText()); + public int getTextFieldIntValue() + { + try + { + return Integer.parseInt(this.getText()); + } + catch (NumberFormatException e) + { + return 0; + } + } + + public void setText(int num) + { + if(this.maxValue < 0 || num <= this.maxValue || num >= this.minValue ) + { + this.setText(Integer.toString(num)); + } } - public void validateTextboxKeyTyped(char c, int key) { + @Override + public void KeyTyped(char c, int key) + { if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT - || (c == '-' && (getCursorPosition() == 0))) - textboxKeyTyped(c, key); + || (c == '-' && (this.getCursorPosition() == 0)) + ) + { + if (Character.isDigit(c) && (this.maxValue > -1 && Integer.parseInt(this.getText() + c) > this.maxValue)) + { + return; + } + super.KeyTyped(c, key); + } + } + + public void setMaxValue(int max) + { + this.maxValue = max; + this.textField.setMaxStringLength(Integer.toString(max).length()); + } + + public void setMinValue(int min) + { + this.minValue = min; } } diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index 67bdb9de..68db827f 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -4,6 +4,7 @@ import mapwriter.map.mapmode.MapMode; import mapwriter.util.Render; +import mapwriter.util.Utils; public class Marker { public final String name; @@ -16,12 +17,6 @@ public class Marker { public Point.Double screenPos = new Point.Double(0, 0); - private static int[] colours = new int[] { - 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, - 0xff8000, 0x8000ff}; - // static so that current index is shared between all markers - private static int colourIndex = 0; - public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { this.name = name; this.x = x; @@ -37,18 +32,14 @@ public String getString() { this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); } - public static int getCurrentColour() { - return 0xff000000 | colours[colourIndex]; - } - - public void colourNext() { - colourIndex = (colourIndex + 1) % colours.length; - this.colour = getCurrentColour(); + public void colourNext() + { + this.colour = Utils.getNextColour(); } - public void colourPrev() { - colourIndex = (colourIndex + colours.length - 1) % colours.length; - this.colour = getCurrentColour(); + public void colourPrev() + { + this.colour = Utils.getPrevColour(); } public void draw(MapMode mapMode, MapView mapView, int borderColour) { diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index 98f85223..ded7fa0a 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; +import mapwriter.Mw; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Logging; import mapwriter.util.Utils; @@ -127,7 +128,12 @@ public void addMarker(String name, String groupName, int x, int y, int z, int di // returns true if the marker exists in the arraylist. // safe to pass null. - public boolean delMarker(Marker markerToDelete) { + public boolean delMarker(Marker markerToDelete) + { + if (this.selectedMarker == markerToDelete) + { + selectedMarker = null; + } return this.markerList.remove(markerToDelete); } diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 734a97f5..36eabeb0 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -205,6 +205,29 @@ public static int getMaxWidth(String[] arr, String[] arr2) return Width; } + private static int[] colours = new int[] { + 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, + 0xff8000, 0x8000ff}; + // static so that current index is shared between all markers + public static int colourIndex = 0; + private static int getColoursLengt() + { + return colours.length; + } + public static int getCurrentColour() { + return 0xff000000 | colours[colourIndex]; + } + public static int getNextColour() + { + Utils.colourIndex = (Utils.colourIndex + 1) % Utils.getColoursLengt(); + return Utils.getCurrentColour(); + } + public static int getPrevColour() { + Utils.colourIndex = (Utils.colourIndex + Utils.getColoursLengt() - 1) % Utils.getColoursLengt(); + return Utils.getCurrentColour(); + } + + /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * @@ -259,7 +282,8 @@ public static int getMaxWidth(String[] arr, String[] arr2) * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true */ @SuppressWarnings("rawtypes") - public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { + public static + Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); Iterator it = rawMap.entrySet().iterator(); while (it.hasNext()) { diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index d9dee529..fa50c618 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -147,6 +147,10 @@ mw.gui.mwguimarkerdialognew.editMarkerGroup=Group mw.gui.mwguimarkerdialognew.editMarkerX=X mw.gui.mwguimarkerdialognew.editMarkerY=Y mw.gui.mwguimarkerdialognew.editMarkerZ=Z - +mw.gui.mwguimarkerdialognew.editMarkerColor=Color mw.gui.mwguimarkerdialognew.title=Teleport Height -mw.gui.mwguimarkerdialognew.error=invalid height \ No newline at end of file +mw.gui.mwguimarkerdialognew.error=invalid height + +mw.gui.ScrollableColorSelector.Red=Red +mw.gui.ScrollableColorSelector.Green=Green +mw.gui.ScrollableColorSelector.Blue=Blue \ No newline at end of file From 4e8f20005b1610170223e836d3d74dbf4c07af80 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sat, 12 Sep 2015 23:57:01 +0200 Subject: [PATCH 076/109] made the release type configurable in the config file. --- build.gradle | 248 +++++++++++++++++++++++------------------------ build.properties | 3 +- 2 files changed, 126 insertions(+), 125 deletions(-) diff --git a/build.gradle b/build.gradle index 2943701d..2626d162 100644 --- a/build.gradle +++ b/build.gradle @@ -1,125 +1,125 @@ -buildscript { - repositories { - mavenCentral() - maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" - } - maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" - } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' - } -} - -apply plugin: 'forge' -apply plugin: 'curseforge' - -repositories { - mavenLocal() -} - -// Define properties file -ext.configFile = file "build.properties" - -configFile.withReader { -// Load config. It shall from now be referenced as simply config or project.config -def prop = new Properties() -prop.load(it) -project.ext.config = new ConfigSlurper().parse prop -} - -dependencies { - if (config.isSet('dependicies')) { - def dep = config.dependicies.split(", ") - dep.each { compile it } - } -} - -group= config.mod_group -version = config.mod_version -archivesBaseName = config.mod_name - - -minecraft { -version = config.mc_version + "-" + config.forge_version -runDir = "eclipse" -mappings = config.mcp_version -replace '@MOD_VERSION@', config.mod_version -} - -processResources -{ - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - - // replace version and mcversion - expand 'version':project.version, 'mcversion':project.minecraft.version - } - - // copy everything else, thats not the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - } -} - -version = "${project.minecraft.version}-${project.version}" - -jar { -//classifier = 'universal' -} - -task sourceJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'src' -} - -task devJar(type: Jar) { -from sourceSets.main.output -classifier = 'dev' -} - -artifacts { - archives sourceJar - archives devJar -} - -eclipse { - // replace absolute paths with classpath variable GRADLE_CACHE - pathVariables 'GRADLE_CACHE': gradle.gradleUserHomeDir -} - -eclipse.classpath.file.whenMerged { classpath -> - classpath.entries.each { entry -> - if (entry.kind == 'lib') { - // for jar files referenced in project folder, use relative path - def prefix = projectDir.absolutePath.replace('\\', '/') - entry.path = entry.path.replace(prefix, "/$eclipse.project.name") - } - } -} - -gradle.taskGraph.whenReady { taskGraph -> - if (!taskGraph.allTasks.findAll{ it.name == 'eclipseClasspath' }.empty) { - gradle.buildFinished { - println '----------------------------------------------------------------------' - print "Please set the Eclipse classpath variable 'GRADLE_USER_HOME' in Preferences " - println "-> Java -> Build path -> Classpath Variable to $gradle.gradleUserHomeDir" - println '----------------------------------------------------------------------' - } - } -} - -curse { - projectId = config.curse_project_id - apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : '' - releaseType = 'release' +buildscript { + repositories { + mavenCentral() + maven { + name = "forge" + url = "http://files.minecraftforge.net/maven" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/repositories/snapshots/" + } + } + dependencies { + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + } +} + +apply plugin: 'forge' +apply plugin: 'curseforge' + +repositories { + mavenLocal() +} + +// Define properties file +ext.configFile = file "build.properties" + +configFile.withReader { +// Load config. It shall from now be referenced as simply config or project.config +def prop = new Properties() +prop.load(it) +project.ext.config = new ConfigSlurper().parse prop +} + +dependencies { + if (config.isSet('dependicies')) { + def dep = config.dependicies.split(", ") + dep.each { compile it } + } +} + +group= config.mod_group +version = config.mod_version +archivesBaseName = config.mod_name + + +minecraft { +version = config.mc_version + "-" + config.forge_version +runDir = "eclipse" +mappings = config.mcp_version +replace '@MOD_VERSION@', config.mod_version +} + +processResources +{ + // this will ensure that this task is redone when the versions change. + inputs.property "version", project.version + inputs.property "mcversion", project.minecraft.version + + // replace stuff in mcmod.info, nothing else + from(sourceSets.main.resources.srcDirs) { + include 'mcmod.info' + + // replace version and mcversion + expand 'version':project.version, 'mcversion':project.minecraft.version + } + + // copy everything else, thats not the mcmod.info + from(sourceSets.main.resources.srcDirs) { + exclude 'mcmod.info' + } +} + +version = "${project.minecraft.version}-${project.version}" + +jar { +//classifier = 'universal' +} + +task sourceJar(type: Jar) { + from sourceSets.main.allSource + classifier = 'src' +} + +task devJar(type: Jar) { +from sourceSets.main.output +classifier = 'dev' +} + +artifacts { + archives sourceJar + archives devJar +} + +eclipse { + // replace absolute paths with classpath variable GRADLE_CACHE + pathVariables 'GRADLE_CACHE': gradle.gradleUserHomeDir +} + +eclipse.classpath.file.whenMerged { classpath -> + classpath.entries.each { entry -> + if (entry.kind == 'lib') { + // for jar files referenced in project folder, use relative path + def prefix = projectDir.absolutePath.replace('\\', '/') + entry.path = entry.path.replace(prefix, "/$eclipse.project.name") + } + } +} + +gradle.taskGraph.whenReady { taskGraph -> + if (!taskGraph.allTasks.findAll{ it.name == 'eclipseClasspath' }.empty) { + gradle.buildFinished { + println '----------------------------------------------------------------------' + print "Please set the Eclipse classpath variable 'GRADLE_USER_HOME' in Preferences " + println "-> Java -> Build path -> Classpath Variable to $gradle.gradleUserHomeDir" + println '----------------------------------------------------------------------' + } + } +} + +curse { + projectId = config.curse_project_id + apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : '' + releaseType = config.release_type } \ No newline at end of file diff --git a/build.properties b/build.properties index f09e73bf..837d1d19 100644 --- a/build.properties +++ b/build.properties @@ -4,4 +4,5 @@ mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 mod_version=2.2.9-Beta -curse_project_id=231387 \ No newline at end of file +curse_project_id=231387 +config.release_type=beta \ No newline at end of file From beb3a989aedb34346aab9425dfacf7d8262dd5c8 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 13 Sep 2015 00:05:47 +0200 Subject: [PATCH 077/109] error --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index 837d1d19..2405d45a 100644 --- a/build.properties +++ b/build.properties @@ -5,4 +5,4 @@ forge_version=11.14.3.1450 mcp_version=snapshot_20150615 mod_version=2.2.9-Beta curse_project_id=231387 -config.release_type=beta \ No newline at end of file +release_type=beta \ No newline at end of file From 718b96d19d5212eeb1ba7720545eff465ebbd875 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 13 Sep 2015 13:49:44 +0200 Subject: [PATCH 078/109] Moved back to 1 task. make chunk update task use the last data set instead of readding the task. should fix some lag problems, and flickering of the map when data is inconsistend --- .../java/mapwriter/BackgroundExecutor.java | 63 +++++++++++++------ src/main/java/mapwriter/ChunkManager.java | 9 +-- src/main/java/mapwriter/gui/MwGui.java | 2 +- .../tasks/UpdateSurfaceChunksTask.java | 35 +++++++++-- 4 files changed, 78 insertions(+), 31 deletions(-) diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index caa5fc26..428df1fe 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -1,15 +1,17 @@ package mapwriter; +import java.util.HashMap; import java.util.LinkedList; +import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import mapwriter.tasks.Task; +import mapwriter.tasks.UpdateSurfaceChunksTask; import mapwriter.util.Logging; - - +import net.minecraft.world.ChunkCoordIntPair; /* This class handles executing and managing 'tasks'. @@ -49,33 +51,47 @@ e.g. addTask(Task1) public class BackgroundExecutor { private ExecutorService executor; - private ExecutorService executor2; private LinkedList taskQueue; + private Map chunksUpdating = new HashMap(); public boolean closed = false; public BackgroundExecutor() { this.executor = Executors.newSingleThreadExecutor(); this.taskQueue = new LinkedList(); - this.executor2 = Executors.newSingleThreadExecutor(); } // add a task to the queue public boolean addTask(Task task) { - if (!this.closed) { - Future future = this.executor.submit(task); - task.setFuture(future); - this.taskQueue.add(task); - } else { - Logging.log("MwExecutor.addTask: error: cannot add task to closed executor"); - } - return this.closed; - } - - public boolean addTask2(Task task) { - if (!this.closed) { - Future future = this.executor2.submit(task); - task.setFuture(future); - this.taskQueue.add(task); + if (!this.closed) + { + if (task instanceof UpdateSurfaceChunksTask) + { + UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; + Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); + + if (!chunksUpdating.containsKey(coords)) + { + Future future = this.executor.submit(task); + task.setFuture(future); + this.taskQueue.add(task); + chunksUpdating.put(coords, task); + } + else + { + UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask)chunksUpdating.get(coords); + if(task2.Running.get() == false) + { + task2.UpdateChunkData(((UpdateSurfaceChunksTask)task).getChunk()); + } + } + } + else + { + Future future = this.executor.submit(task); + task.setFuture(future); + this.taskQueue.add(task); + } + } else { Logging.log("MwExecutor.addTask: error: cannot add task to closed executor"); } @@ -92,6 +108,15 @@ public boolean processTaskQueue() { if (task.isDone()) { task.printException(); task.onComplete(); + + if (task instanceof UpdateSurfaceChunksTask) + { + UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; + Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); + + chunksUpdating.remove(coords, updatetask); + + } processed = true; } else { // put entry back on top of queue diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index 55092a0e..b338c9b8 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -121,13 +121,14 @@ public void updateSurfaceChunks() { if ((flags & VISIBLE_FLAG) != 0) { chunkArray[i] = copyToMwChunk(chunk); + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray[i])); } else { chunkArray[i] = null; } } } - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + //this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); } public void onTick() { @@ -140,15 +141,11 @@ public void onTick() { } } - public void forceChunks(MwChunk[] chunkArray){ - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - private void addSaveChunkTask(Chunk chunk) { if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { if (!chunk.isEmpty()) { - this.mw.executor.addTask2(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); } } } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index bf5d06cb..8f8d00e5 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -348,7 +348,7 @@ public void regenerateView() { (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); // this.mw.reloadBlockColours(); - this.mw.executor.addTask2(new RebuildRegionsTask(this.mw, + this.mw.executor.addTask(new RebuildRegionsTask(this.mw, (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), this.mapView.getDimension())); diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java index b71c00da..81b7ba45 100644 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -1,24 +1,29 @@ package mapwriter.tasks; +import java.util.concurrent.atomic.AtomicBoolean; + import mapwriter.Mw; import mapwriter.map.MapTexture; import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; +import mapwriter.util.Logging; public class UpdateSurfaceChunksTask extends Task { - MwChunk[] chunkArray; + MwChunk chunk; RegionManager regionManager; MapTexture mapTexture; + public AtomicBoolean Running = new AtomicBoolean(); - public UpdateSurfaceChunksTask(Mw mw, MwChunk[] chunkArray) { + public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) { this.mapTexture = mw.mapTexture; this.regionManager = mw.regionManager; - this.chunkArray = chunkArray; + this.chunk = chunk; } @Override public void run() { - for (MwChunk chunk : this.chunkArray) { + Running.set(true);; + //for (MwChunk chunk : this.chunkArray) { if (chunk != null) { // update the chunk in the region pixels this.regionManager.updateChunk(chunk); @@ -29,10 +34,30 @@ public void run() { MwChunk.SIZE, MwChunk.SIZE, chunk.dimension ); } - } + //} + Running.set(false); } @Override public void onComplete() { } + + public int getChunkX() + { + return chunk.x; + } + + public int getChunkZ() + { + return chunk.z; + } + + public void UpdateChunkData(MwChunk chunk) + { + this.chunk = chunk; + } + public MwChunk getChunk() + { + return this.chunk; + } } From e8a0ec00a2126fcbf27ca3863891e1a59e048684 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 13 Sep 2015 13:53:25 +0200 Subject: [PATCH 079/109] removed the logging stuff from Regionmanager --- .../java/mapwriter/region/BlockColours.java | 20 +++++++------ .../java/mapwriter/region/MergeToImage.java | 6 ++-- src/main/java/mapwriter/region/MwChunk.java | 29 +++++------------- .../java/mapwriter/region/RegionFile.java | 26 ++++++++-------- .../java/mapwriter/region/RegionManager.java | 30 +++++-------------- .../java/mapwriter/region/SurfacePixels.java | 6 ++-- 6 files changed, 48 insertions(+), 69 deletions(-) diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index ac1ee4a0..813842b6 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -15,6 +15,7 @@ import java.util.Map.Entry; import java.util.Scanner; +import mapwriter.util.Logging; import mapwriter.util.Render; import net.minecraft.block.Block; @@ -163,7 +164,7 @@ private static BlockType getBlockTypeFromString(String typeString) { } else if (typeString.equalsIgnoreCase("opaque")) { blockType = BlockType.OPAQUE; } else { - RegionManager.logWarning("unknown block type '%s'", typeString); + Logging.logWarning("unknown block type '%s'", typeString); } return blockType; } @@ -306,12 +307,12 @@ private void loadBiomeLine(String[] split) { this.setBiomeFoliageShading(biomeId, foliageMultiplier); } } else { - RegionManager.logWarning("biome ID '%d' out of range", + Logging.logWarning("biome ID '%d' out of range", startBiomeId); } } catch (NumberFormatException e) { - RegionManager.logWarning( + Logging.logWarning( "invalid biome colour line '%s %s %s %s %s'", split[0], split[1], split[2], split[3], split[4]); } @@ -330,7 +331,7 @@ private void loadBlockLine(String[] split) { this.setColour(split[1], split[2], colour); } catch (NumberFormatException e) { - RegionManager.logWarning("invalid block colour line '%s %s %s %s'", + Logging.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); } } @@ -341,7 +342,7 @@ private void loadBlockTypeLine(String[] split) { BlockType type = getBlockTypeFromString(split[3]); this.setBlockType(split[1], split[2], type); } catch (NumberFormatException e) { - RegionManager.logWarning("invalid block colour line '%s %s %s %s'", + Logging.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); } } @@ -365,13 +366,13 @@ public void loadFromFile(File f) { && (lineSplit.length == 4)) { this.loadBlockTypeLine(lineSplit); } else { - RegionManager.logWarning( + Logging.logWarning( "invalid map colour line '%s'", line); } } } } catch (IOException e) { - RegionManager.logError("loading block colours: no such file '%s'", + Logging.logError("loading block colours: no such file '%s'", f); } finally { @@ -521,7 +522,7 @@ public void saveToFile(File f) { this.saveBlocks(fout); } catch (IOException e) { - RegionManager.logError( + Logging.logError( "saving block colours: could not write to '%s'", f); } finally { @@ -557,6 +558,7 @@ public static void writeOverridesFile(File f) { + "blocktype minecraft:flowing_water * water # flowing water block\n" + "blocktype minecraft:water * water # still water block\n" + "blocktype minecraft:leaves * leaves # leaves block\n" + + "blocktype minecraft:leaves2 * leaves # leaves block\n" + "blocktype minecraft:leaves 1 opaque # pine leaves (not biome colorized)\n" + "blocktype minecraft:leaves 2 opaque # birch leaves (not biome colorized)\n" + "blocktype minecraft:tallgrass * grass # tall grass block\n" @@ -585,7 +587,7 @@ public static void writeOverridesFile(File f) { // + "blocktype 3278 * opaque # natura rare leaves\n" // + "blocktype 3258 * opaque # natura sakura leaves\n" } catch (IOException e) { - RegionManager.logError( + Logging.logError( "saving block overrides: could not write to '%s'", f); } finally { diff --git a/src/main/java/mapwriter/region/MergeToImage.java b/src/main/java/mapwriter/region/MergeToImage.java index 79ac3cbf..f4634498 100644 --- a/src/main/java/mapwriter/region/MergeToImage.java +++ b/src/main/java/mapwriter/region/MergeToImage.java @@ -6,6 +6,8 @@ import javax.imageio.ImageIO; +import mapwriter.util.Logging; + public class MergeToImage { public static final int MAX_WIDTH = 8192; public static final int MAX_HEIGHT = 8192; @@ -62,7 +64,7 @@ public static int merge(RegionManager regionManager, int xCentre, int zCentre, i int xMax = xMin + w; int zMax = zMin + h; - RegionManager.logInfo("merging area starting at (%d,%d), %dx%d blocks", + Logging.logInfo("merging area starting at (%d,%d), %dx%d blocks", xMin, zMin, w, h); @@ -76,7 +78,7 @@ public static int merge(RegionManager regionManager, int xCentre, int zCentre, i String imgName = String.format("%s.%d.%d.png", basename, countX, countZ); File f = new File(dir, imgName); - RegionManager.logInfo("merging regions to image %s", f); + Logging.logInfo("merging regions to image %s", f); BufferedImage img = mergeRegions(regionManager, x, z, imgW, imgH, dimension); writeImage(img, f); diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index e8a6ebef..2c36b50b 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; +import mapwriter.util.Logging; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; @@ -118,9 +119,7 @@ public static MwChunk read(int x, int z, int dimension, int zNbt = level.getInteger("zPos"); if ((xNbt != x) || (zNbt != z)) { - RegionManager.logWarning( - "chunk (%d, %d) has NBT coords (%d, %d)", x, z, - xNbt, zNbt); + Logging.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); } NBTTagList sections = level.getTagList("Sections", 10); @@ -165,15 +164,12 @@ public static MwChunk read(int x, int z, int dimension, } } catch (IOException e) { - RegionManager.logError( - "%s: could not read chunk (%d, %d) from region file\n", - e, x, z); + Logging.logError("%s: could not read chunk (%d, %d) from region file\n",e, x, z); } finally { try { dis.close(); } catch (IOException e) { - RegionManager.logError( - "MwChunk.read: %s while closing input stream", e); + Logging.logError("MwChunk.read: %s while closing input stream", e); } } // this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, @@ -422,29 +418,20 @@ public synchronized boolean write(RegionFileCache regionFileCache) { // Data CompressedStreamTools.write(writeChunkToNBT(), dos); } catch (IOException e) { - RegionManager - .logError( - "%s: could not write chunk (%d, %d) to region file", - e, this.x, this.z); + Logging.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); error = true; } finally { try { dos.close(); } catch (IOException e) { - RegionManager.logError( - "%s while closing chunk data output stream", e); + Logging.logError( "%s while closing chunk data output stream", e); } } } else { - RegionManager - .logError( - "error: could not get output stream for chunk (%d, %d)", - this.x, this.z); + Logging.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); } } else { - RegionManager.logError( - "error: could not open region file for chunk (%d, %d)", - this.x, this.z); + Logging.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); } return error; diff --git a/src/main/java/mapwriter/region/RegionFile.java b/src/main/java/mapwriter/region/RegionFile.java index 28047833..a06119bc 100644 --- a/src/main/java/mapwriter/region/RegionFile.java +++ b/src/main/java/mapwriter/region/RegionFile.java @@ -14,6 +14,8 @@ import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; +import mapwriter.util.Logging; + /* Anvil region file reader/writer implementation. This code is very similar to RegionFile and RegionFileChunkBuffer from Minecraft. @@ -71,7 +73,7 @@ private void setFilledSectorArray(Section section, boolean filled) { } for (int i = section.startSector; i < endSector; i++) { if (filled && this.filledSectorArray.get(i)) { - RegionManager.logError("sector %d already filled, possible chunk overlap", i); + Logging.logError("sector %d already filled, possible chunk overlap", i); } this.filledSectorArray.set(i, Boolean.valueOf(filled)); } @@ -144,7 +146,7 @@ public void printInfo() { freeCount++; } } - RegionManager.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); + Logging.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); String s = ""; int i; @@ -154,11 +156,11 @@ public void printInfo() { } s += this.filledSectorArray.get(i) ? '1' : '0'; if ((i & 31) == 31) { - RegionManager.logInfo("%s", s); + Logging.logInfo("%s", s); } } if ((i & 31) != 31) { - RegionManager.logInfo("%s", s); + Logging.logInfo("%s", s); } } @@ -182,12 +184,12 @@ public boolean open() { File dir = this.file.getParentFile(); if (dir.exists()) { if (!dir.isDirectory()) { - RegionManager.logError("path %s exists and is not a directory", dir); + Logging.logError("path %s exists and is not a directory", dir); return true; } } else { if (!dir.mkdirs()) { - RegionManager.logError("could not create directory %s", dir); + Logging.logError("could not create directory %s", dir); return true; } } @@ -220,7 +222,7 @@ public boolean open() { this.chunkSectionsArray[i] = section; this.setFilledSectorArray(section, true); } else { - RegionManager.logError("chunk %d overlaps another chunk, file may be corrupt", i); + Logging.logError("chunk %d overlaps another chunk, file may be corrupt", i); } } } @@ -233,7 +235,7 @@ public boolean open() { } catch (Exception e) { this.fin = null; - RegionManager.logError("exception when opening region file '%s': %s", this.file, e); + Logging.logError("exception when opening region file '%s': %s", this.file, e); } @@ -266,10 +268,10 @@ public DataInputStream getChunkDataInputStream(int x, int z) { // create a buffered inflater stream on the compressed data dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(compressedChunkData)))); } else { - RegionManager.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); + Logging.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); } } catch (Exception e) { - RegionManager.logError("exception while reading chunk (%d, %d): %s", x, z, e); + Logging.logError("exception while reading chunk (%d, %d): %s", x, z, e); dis = null; } } @@ -331,7 +333,7 @@ private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, i // free sectors longer than the length of the chunk data, or the end of the file (append). if (length <= 0) { - RegionManager.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); + Logging.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); return true; } @@ -364,7 +366,7 @@ private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, i this.updateChunkSection(x, z, newSection); error = false; } catch (IOException e) { - RegionManager.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); + Logging.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); } return error; diff --git a/src/main/java/mapwriter/region/RegionManager.java b/src/main/java/mapwriter/region/RegionManager.java index 7d9d7c61..425f2924 100644 --- a/src/main/java/mapwriter/region/RegionManager.java +++ b/src/main/java/mapwriter/region/RegionManager.java @@ -6,6 +6,8 @@ import java.util.Map; import java.util.Map.Entry; +import mapwriter.util.Logging; + import org.apache.logging.log4j.Logger; public class RegionManager { @@ -45,24 +47,6 @@ protected boolean removeEldestEntry(Map.Entry entry) { public int maxZoom; public int minZoom; - public static void logInfo(String s, Object...args) { - if (logger != null) { - logger.info(String.format(s, args)); - } - } - - public static void logWarning(String s, Object...args) { - if (logger != null) { - logger.warn(String.format(s, args)); - } - } - - public static void logError(String s, Object...args) { - if (logger != null) { - logger.error(String.format(s, args)); - } - } - public RegionManager(File worldDir, File imageDir, BlockColours blockColours, int minZoom, int maxZoom) { this.worldDir = worldDir; this.imageDir = imageDir; @@ -93,17 +77,17 @@ private static int incrStatsCounter(Map h, String key) { } public void printLoadedRegionStats() { - logInfo("loaded region listing:"); + Logging.logInfo("loaded region listing:"); Map stats = new HashMap(); for (Region region : this.regionMap.values()) { - logInfo(" %s", region); + Logging.logInfo(" %s", region); incrStatsCounter(stats, String.format("dim%d", region.dimension)); incrStatsCounter(stats, String.format("zoom%d", region.zoomLevel)); incrStatsCounter(stats, "total"); } - logInfo("loaded region stats:"); + Logging.logInfo("loaded region stats:"); for (Entry e : stats.entrySet()) { - logInfo(" %s: %d", e.getKey(), e.getValue()); + Logging.logInfo(" %s: %d", e.getKey(), e.getValue()); } } @@ -132,7 +116,7 @@ public void rebuildRegions(int xStart, int zStart, int w, int h, int dimension) w = (w + Region.SIZE) & Region.MASK; h = (h + Region.SIZE) & Region.MASK; - logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); + Logging.logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); for (int rX = xStart; rX < (xStart + w); rX += Region.SIZE) { for (int rZ = zStart; rZ < (zStart + h); rZ += Region.SIZE) { diff --git a/src/main/java/mapwriter/region/SurfacePixels.java b/src/main/java/mapwriter/region/SurfacePixels.java index 47554348..38ca62ee 100644 --- a/src/main/java/mapwriter/region/SurfacePixels.java +++ b/src/main/java/mapwriter/region/SurfacePixels.java @@ -7,6 +7,8 @@ import javax.imageio.ImageIO; +import mapwriter.util.Logging; + public class SurfacePixels { protected Region region; @@ -131,7 +133,7 @@ public static void saveImage(File filename, int[] pixels, int w, int h) { //MwUtil.log("writing region %s to %s", this, this.imageFile); ImageIO.write(img, "png", filename); } catch (IOException e) { - RegionManager.logError("saveImage: error: could not write image to %s", filename); + Logging.logError("saveImage: error: could not write image to %s", filename); } } @@ -148,7 +150,7 @@ public static int[] loadImage(File filename, int w, int h) { pixels = new int[w * h]; img.getRGB(0, 0, w, h, pixels, 0, w); } else { - RegionManager.logWarning( + Logging.logWarning( "loadImage: image '%s' does not match expected dimensions (got %dx%d expected %dx%d)", filename, img.getWidth(), img.getHeight(), w, h ); From 635e0b477b236690ddcdb8244f0b903c4f35ca46 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 14 Sep 2015 21:17:33 +0200 Subject: [PATCH 080/109] upped beta version to see if the memory leak is fixed --- build.properties | 2 +- src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.properties b/build.properties index 2405d45a..465ce931 100644 --- a/build.properties +++ b/build.properties @@ -3,6 +3,6 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 -mod_version=2.2.9-Beta +mod_version=2.2.9-Beta-2 curse_project_id=231387 release_type=beta \ No newline at end of file diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java index 81b7ba45..75723738 100644 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -22,7 +22,7 @@ public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) { @Override public void run() { - Running.set(true);; + Running.set(true); //for (MwChunk chunk : this.chunkArray) { if (chunk != null) { // update the chunk in the region pixels From e8178c6f2d09dd77b93dbf3256d0470c92ae881b Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 00:06:34 +0200 Subject: [PATCH 081/109] Added inworld markers. configuration to disable the different aspects of the markers --- src/main/java/mapwriter/config/Config.java | 7 +- .../config/ConfigurationHandler.java | 5 +- .../java/mapwriter/forge/EventHandler.java | 10 + src/main/java/mapwriter/map/Marker.java | 148 ++-- .../java/mapwriter/map/MarkerManager.java | 771 +++++++++++------- .../assets/mapwriter/lang/en_US.lang | 9 +- 6 files changed, 590 insertions(+), 360 deletions(-) diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 47a3cb8b..e7412677 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -50,7 +50,12 @@ public class Config { public static boolean moreRealisticMap = moreRealisticMapDef; public static boolean newMarkerDialogDef = true; public static boolean newMarkerDialog = newMarkerDialogDef; - + public static boolean drawMarkersInWorldDef = false; + public static boolean drawMarkersInWorld = drawMarkersInWorldDef; + public static boolean drawMarkersNameInWorldDef = false; + public static boolean drawMarkersNameInWorld = drawMarkersNameInWorldDef; + public static boolean drawMarkersDistanceInWorldDef = false; + public static boolean drawMarkersDistanceInWorld = drawMarkersDistanceInWorldDef; //World configuration Options public static int overlayModeIndexDef = 0; diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index fec469b9..5f46bfe5 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -50,7 +50,10 @@ public static void loadConfig() Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "mw.config.newMarkerDialog"); - + Config.drawMarkersInWorld = configuration.getBoolean("drawMarkersInWorld", Reference.catOptions, Config.drawMarkersInWorldDef, "mw.config.drawMarkersInWorld"); + Config.drawMarkersNameInWorld = configuration.getBoolean("drawMarkersNameInWorld", Reference.catOptions, Config.drawMarkersNameInWorldDef, "mw.config.drawMarkersNameInWorld"); + Config.drawMarkersDistanceInWorld = configuration.getBoolean("drawMarkersDistanceInWorld", Reference.catOptions, Config.drawMarkersDistanceInWorldDef, "mw.config.drawMarkersDistanceInWorld"); + Config.fullScreenMap.loadConfig(); Config.largeMap.loadConfig(); Config.smallMap.loadConfig(); diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index ed4a95af..561ac5ef 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -7,6 +7,7 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.ChunkEvent; @@ -84,4 +85,13 @@ public void renderMap(RenderGameOverlayEvent.Post event){ public void onTextureStitchEventPost(TextureStitchEvent.Post event){ mw.reloadBlockColours(); } + + @SubscribeEvent + public void renderWorldLastEvent(RenderWorldLastEvent event) + { + if (Mw.getInstance().ready) + { + Mw.getInstance().markerManager.drawMarkersWorld(event.partialTicks); + } + } } diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index 68db827f..d900bf71 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -1,70 +1,80 @@ -package mapwriter.map; - -import java.awt.Point; - -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Render; -import mapwriter.util.Utils; - -public class Marker { - public final String name; - public final String groupName; - public int x; - public int y; - public int z; - public int dimension; - public int colour; - - public Point.Double screenPos = new Point.Double(0, 0); - - public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - this.name = name; - this.x = x; - this.y = y; - this.z = z; - this.dimension = dimension; - this.colour = colour; - this.groupName = groupName; - } - - public String getString() { - return String.format("%s %s (%d, %d, %d) %d %06x", - this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); - } - - public void colourNext() - { - this.colour = Utils.getNextColour(); - } - - public void colourPrev() - { - this.colour = Utils.getPrevColour(); - } - - public void draw(MapMode mapMode, MapView mapView, int borderColour) { - double scale = mapView.getDimensionScaling(this.dimension); - Point.Double p = mapMode.getClampedScreenXY(mapView, this.x * scale, this.z * scale); - this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); - - // draw a coloured rectangle centered on the calculated (x, y) - double mSize = mapMode.config.markerSize; - double halfMSize = mapMode.config.markerSize / 2.0; - Render.setColour(borderColour); - Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); - Render.setColour(this.colour); - Render.drawRect(p.x - halfMSize + 0.5, p.y - halfMSize + 0.5, mSize - 1.0, mSize - 1.0); - } - - // arraylist.contains was producing unexpected results in some situations - // rather than figure out why i'll just control how two markers are compared - @Override - public boolean equals(final Object o) { - if (this == o) { return true; } - if (o instanceof Marker) { - Marker m = (Marker) o; - return (name == m.name) && (groupName == m.groupName) && (x == m.x) && (y == m.y) && (z == m.z) && (dimension == m.dimension); - } - return false; - } +package mapwriter.map; + +import java.awt.Point; + +import net.minecraft.entity.Entity; +import net.minecraft.util.MathHelper; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Render; +import mapwriter.util.Utils; + +public class Marker { + public final String name; + public final String groupName; + public int x; + public int y; + public int z; + public int dimension; + public int colour; + + public Point.Double screenPos = new Point.Double(0, 0); + + public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + this.name = name; + this.x = x; + this.y = y; + this.z = z; + this.dimension = dimension; + this.colour = colour; + this.groupName = groupName; + } + + public String getString() { + return String.format("%s %s (%d, %d, %d) %d %06x", + this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); + } + + public void colourNext() + { + this.colour = Utils.getNextColour(); + } + + public void colourPrev() + { + this.colour = Utils.getPrevColour(); + } + + public void draw(MapMode mapMode, MapView mapView, int borderColour) { + double scale = mapView.getDimensionScaling(this.dimension); + Point.Double p = mapMode.getClampedScreenXY(mapView, this.x * scale, this.z * scale); + this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); + + // draw a coloured rectangle centered on the calculated (x, y) + double mSize = mapMode.config.markerSize; + double halfMSize = mapMode.config.markerSize / 2.0; + Render.setColour(borderColour); + Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); + Render.setColour(this.colour); + Render.drawRect(p.x - halfMSize + 0.5, p.y - halfMSize + 0.5, mSize - 1.0, mSize - 1.0); + } + + // arraylist.contains was producing unexpected results in some situations + // rather than figure out why i'll just control how two markers are compared + @Override + public boolean equals(final Object o) { + if (this == o) { return true; } + if (o instanceof Marker) { + Marker m = (Marker) o; + return (name == m.name) && (groupName == m.groupName) && (x == m.x) && (y == m.y) && (z == m.z) && (dimension == m.dimension); + } + return false; + } + + public double getDistanceToMarker(Entity entityIn) + { + double d0 = this.x - entityIn.posX; + double d1 = this.y - entityIn.posY; + double d2 = this.z - entityIn.posZ; + return (double)MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index ded7fa0a..3c724713 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -1,286 +1,485 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.map.mapmode.MapMode; -import mapwriter.util.Logging; -import mapwriter.util.Utils; -import net.minecraftforge.common.config.Configuration; - -public class MarkerManager { - - public List markerList = new ArrayList(); - public List groupList = new ArrayList(); - - public List visibleMarkerList = new ArrayList(); - - private String visibleGroupName = "none"; - - public Marker selectedMarker = null; - - public MarkerManager() { - } - - public void load(Configuration config, String category) { - this.markerList.clear(); - - if (config.hasCategory(category)) { - int markerCount = config.get(category, "markerCount", 0).getInt(); - this.visibleGroupName = config.get(category, "visibleGroup", "").getString(); - - if (markerCount > 0) { - for (int i = 0; i < markerCount; i++) { - String key = "marker" + i; - String value = config.get(category, key, "").getString(); - Marker marker = this.stringToMarker(value); - if (marker != null) { - this.addMarker(marker); - } else { - Logging.log("error: could not load " + key + " from config file"); - } - } - } - } - - this.update(); - } - - public void save(Configuration config, String category) { - config.get(category, "markerCount", 0).set(this.markerList.size()); - config.get(category, "visibleGroup", "").set(this.visibleGroupName); - - int i = 0; - for (Marker marker : this.markerList) { - String key = "marker" + i; - String value = this.markerToString(marker); - config.get(category, key, "").set(value); - i++; - } - } - - public void setVisibleGroupName(String groupName) { - if (groupName != null) { - this.visibleGroupName = Utils.mungeString(groupName); - } else { - this.visibleGroupName = "none"; - } - } - - public String getVisibleGroupName() { - return this.visibleGroupName; - } - - public void clear() { - this.markerList.clear(); - this.groupList.clear(); - this.visibleMarkerList.clear(); - this.visibleGroupName = "none"; - } - - public String markerToString(Marker marker) { - return String.format("%s:%d:%d:%d:%d:%06x:%s", - marker.name, - marker.x, marker.y, marker.z, - marker.dimension, - marker.colour & 0xffffff, - marker.groupName - ); - } - - public Marker stringToMarker(String s) { - // new style delimited with colons - String[] split = s.split(":"); - if (split.length != 7) { - // old style was space delimited - split = s.split(" "); - } - Marker marker = null; - if (split.length == 7) { - try { - int x = Integer.parseInt(split[1]); - int y = Integer.parseInt(split[2]); - int z = Integer.parseInt(split[3]); - int dimension = Integer.parseInt(split[4]); - int colour = 0xff000000 | Integer.parseInt(split[5], 16); - - marker = new Marker(split[0], split[6], x, y, z, dimension, colour); - - } catch (NumberFormatException e) { - marker = null; - } - } else { - Logging.log("Marker.stringToMarker: invalid marker '%s'", s); - } - return marker; - } - - public void addMarker(Marker marker) { - this.markerList.add(marker); - } - - public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - name = name.replace(":", ""); - groupName = groupName.replace(":", ""); - this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); - } - - // returns true if the marker exists in the arraylist. - // safe to pass null. - public boolean delMarker(Marker markerToDelete) - { - if (this.selectedMarker == markerToDelete) - { - selectedMarker = null; - } - return this.markerList.remove(markerToDelete); - } - - // deletes the first marker with matching name and group. - // if null is passed as either name or group it means "any". - public boolean delMarker(String name, String group) { - Marker markerToDelete = null; - for (Marker marker : this.markerList) { - if (((name == null) || marker.name.equals(name)) && - ((group == null) || marker.groupName.equals(group))) { - markerToDelete = marker; - break; - } - } - // will return false if a marker matching the criteria is not found - // (i.e. if markerToDelete is null) - return this.delMarker(markerToDelete); - } - - /*public boolean delGroup(String groupName) { - boolean error = !this.groupList.remove(groupName); - Iterator it = this.markerMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - Marker marker = (Marker) entry.getValue(); - if (marker.groupName.equals(groupName)) { - it.remove(); - } - } - if (groupName == this.visibleGroupName) { - this.nextGroup(); - } - return error; - }*/ - - public void update() { - this.visibleMarkerList.clear(); - this.groupList.clear(); - this.groupList.add("none"); - this.groupList.add("all"); - for (Marker marker : this.markerList) { - if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) { - this.visibleMarkerList.add(marker); - } - if (!this.groupList.contains(marker.groupName)) { - this.groupList.add(marker.groupName); - } - } - if (!this.groupList.contains(this.visibleGroupName)) { - this.visibleGroupName = "none"; - } - } - - public void nextGroup(int n) { - if (this.groupList.size() > 0) { - int i = this.groupList.indexOf(this.visibleGroupName); - int size = this.groupList.size(); - if (i != -1) { - i = (i + size + n) % size; - } else { - i = 0; - } - this.visibleGroupName = this.groupList.get(i); - } else { - this.visibleGroupName = "none"; - this.groupList.add("none"); - } - } - - public void nextGroup() { - this.nextGroup(1); - } - - public int countMarkersInGroup(String group) { - int count = 0; - if (group.equals("all")) { - count = this.markerList.size(); - } else { - for (Marker marker : this.markerList) { - if (marker.groupName.equals(group)) { - count++; - } - } - } - return count; - } - - public void selectNextMarker() { - if (this.visibleMarkerList.size() > 0) { - int i = 0; - if (this.selectedMarker != null) { - i = this.visibleMarkerList.indexOf(this.selectedMarker); - if (i == -1) { - i = 0; - } - } - i = (i + 1) % this.visibleMarkerList.size(); - this.selectedMarker = this.visibleMarkerList.get(i); - } else { - this.selectedMarker = null; - } - } - - public Marker getNearestMarker(int x, int z, int maxDistance) { - int nearestDistance = maxDistance * maxDistance; - Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { - int dx = x - marker.x; - int dz = z - marker.z; - int d = (dx * dx) + (dz * dz); - if (d < nearestDistance) { - nearestMarker = marker; - nearestDistance = d; - } - } - return nearestMarker; - } - - public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { - int nearestDistance = 10000 * 10000; - Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { - int dx = marker.x - x; - int dz = marker.z - z; - int d = (dx * dx) + (dz * dz); - double angle = Math.atan2(dz, dx); - // use cos instead of abs as it will wrap at 2 * Pi. - // cos will be closer to 1.0 the closer desiredAngle and angle are. - // 0.8 is the threshold corresponding to a maximum of - // acos(0.8) = 37 degrees difference between the two angles. - if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) { - nearestMarker = marker; - nearestDistance = d; - } - } - return nearestMarker; - } - - public void drawMarkers(MapMode mapMode, MapView mapView) { - for (Marker marker : this.visibleMarkerList) { - // only draw markers that were set in the current dimension - if (mapView.getDimension() == marker.dimension) { - marker.draw(mapMode, mapView, 0xff000000); - } - } - if (this.selectedMarker != null) { - this.selectedMarker.draw(mapMode, mapView, 0xffffffff); - } - } -} +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.config.Config; +import mapwriter.map.mapmode.MapMode; +import mapwriter.util.Logging; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraftforge.common.config.Configuration; + +import org.lwjgl.opengl.GL11; +import static org.lwjgl.opengl.ARBDepthClamp.GL_DEPTH_CLAMP; + +public class MarkerManager { + + public List markerList = new ArrayList(); + public List groupList = new ArrayList(); + + public List visibleMarkerList = new ArrayList(); + + private String visibleGroupName = "none"; + + public Marker selectedMarker = null; + + public MarkerManager() { + } + + public void load(Configuration config, String category) { + this.markerList.clear(); + + if (config.hasCategory(category)) { + int markerCount = config.get(category, "markerCount", 0).getInt(); + this.visibleGroupName = config.get(category, "visibleGroup", "").getString(); + + if (markerCount > 0) { + for (int i = 0; i < markerCount; i++) { + String key = "marker" + i; + String value = config.get(category, key, "").getString(); + Marker marker = this.stringToMarker(value); + if (marker != null) { + this.addMarker(marker); + } else { + Logging.log("error: could not load " + key + " from config file"); + } + } + } + } + + this.update(); + } + + public void save(Configuration config, String category) { + config.get(category, "markerCount", 0).set(this.markerList.size()); + config.get(category, "visibleGroup", "").set(this.visibleGroupName); + + int i = 0; + for (Marker marker : this.markerList) { + String key = "marker" + i; + String value = this.markerToString(marker); + config.get(category, key, "").set(value); + i++; + } + } + + public void setVisibleGroupName(String groupName) { + if (groupName != null) { + this.visibleGroupName = Utils.mungeString(groupName); + } else { + this.visibleGroupName = "none"; + } + } + + public String getVisibleGroupName() { + return this.visibleGroupName; + } + + public void clear() { + this.markerList.clear(); + this.groupList.clear(); + this.visibleMarkerList.clear(); + this.visibleGroupName = "none"; + } + + public String markerToString(Marker marker) { + return String.format("%s:%d:%d:%d:%d:%06x:%s", + marker.name, + marker.x, marker.y, marker.z, + marker.dimension, + marker.colour & 0xffffff, + marker.groupName + ); + } + + public Marker stringToMarker(String s) { + // new style delimited with colons + String[] split = s.split(":"); + if (split.length != 7) { + // old style was space delimited + split = s.split(" "); + } + Marker marker = null; + if (split.length == 7) { + try { + int x = Integer.parseInt(split[1]); + int y = Integer.parseInt(split[2]); + int z = Integer.parseInt(split[3]); + int dimension = Integer.parseInt(split[4]); + int colour = 0xff000000 | Integer.parseInt(split[5], 16); + + marker = new Marker(split[0], split[6], x, y, z, dimension, colour); + + } catch (NumberFormatException e) { + marker = null; + } + } else { + Logging.log("Marker.stringToMarker: invalid marker '%s'", s); + } + return marker; + } + + public void addMarker(Marker marker) { + this.markerList.add(marker); + } + + public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + name = name.replace(":", ""); + groupName = groupName.replace(":", ""); + this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); + } + + // returns true if the marker exists in the arraylist. + // safe to pass null. + public boolean delMarker(Marker markerToDelete) + { + if (this.selectedMarker == markerToDelete) + { + selectedMarker = null; + } + return this.markerList.remove(markerToDelete); + } + + // deletes the first marker with matching name and group. + // if null is passed as either name or group it means "any". + public boolean delMarker(String name, String group) { + Marker markerToDelete = null; + for (Marker marker : this.markerList) { + if (((name == null) || marker.name.equals(name)) && + ((group == null) || marker.groupName.equals(group))) { + markerToDelete = marker; + break; + } + } + // will return false if a marker matching the criteria is not found + // (i.e. if markerToDelete is null) + return this.delMarker(markerToDelete); + } + + /*public boolean delGroup(String groupName) { + boolean error = !this.groupList.remove(groupName); + Iterator it = this.markerMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Marker marker = (Marker) entry.getValue(); + if (marker.groupName.equals(groupName)) { + it.remove(); + } + } + if (groupName == this.visibleGroupName) { + this.nextGroup(); + } + return error; + }*/ + + public void update() { + this.visibleMarkerList.clear(); + this.groupList.clear(); + this.groupList.add("none"); + this.groupList.add("all"); + for (Marker marker : this.markerList) { + if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) { + this.visibleMarkerList.add(marker); + } + if (!this.groupList.contains(marker.groupName)) { + this.groupList.add(marker.groupName); + } + } + if (!this.groupList.contains(this.visibleGroupName)) { + this.visibleGroupName = "none"; + } + } + + public void nextGroup(int n) { + if (this.groupList.size() > 0) { + int i = this.groupList.indexOf(this.visibleGroupName); + int size = this.groupList.size(); + if (i != -1) { + i = (i + size + n) % size; + } else { + i = 0; + } + this.visibleGroupName = this.groupList.get(i); + } else { + this.visibleGroupName = "none"; + this.groupList.add("none"); + } + } + + public void nextGroup() { + this.nextGroup(1); + } + + public int countMarkersInGroup(String group) { + int count = 0; + if (group.equals("all")) { + count = this.markerList.size(); + } else { + for (Marker marker : this.markerList) { + if (marker.groupName.equals(group)) { + count++; + } + } + } + return count; + } + + public void selectNextMarker() { + if (this.visibleMarkerList.size() > 0) { + int i = 0; + if (this.selectedMarker != null) { + i = this.visibleMarkerList.indexOf(this.selectedMarker); + if (i == -1) { + i = 0; + } + } + i = (i + 1) % this.visibleMarkerList.size(); + this.selectedMarker = this.visibleMarkerList.get(i); + } else { + this.selectedMarker = null; + } + } + + public Marker getNearestMarker(int x, int z, int maxDistance) { + int nearestDistance = maxDistance * maxDistance; + Marker nearestMarker = null; + for (Marker marker : this.visibleMarkerList) { + int dx = x - marker.x; + int dz = z - marker.z; + int d = (dx * dx) + (dz * dz); + if (d < nearestDistance) { + nearestMarker = marker; + nearestDistance = d; + } + } + return nearestMarker; + } + + public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { + int nearestDistance = 10000 * 10000; + Marker nearestMarker = null; + for (Marker marker : this.visibleMarkerList) { + int dx = marker.x - x; + int dz = marker.z - z; + int d = (dx * dx) + (dz * dz); + double angle = Math.atan2(dz, dx); + // use cos instead of abs as it will wrap at 2 * Pi. + // cos will be closer to 1.0 the closer desiredAngle and angle are. + // 0.8 is the threshold corresponding to a maximum of + // acos(0.8) = 37 degrees difference between the two angles. + if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) { + nearestMarker = marker; + nearestDistance = d; + } + } + return nearestMarker; + } + + public void drawMarkers(MapMode mapMode, MapView mapView) { + for (Marker marker : this.visibleMarkerList) { + // only draw markers that were set in the current dimension + if (mapView.getDimension() == marker.dimension) { + marker.draw(mapMode, mapView, 0xff000000); + } + } + if (this.selectedMarker != null) { + this.selectedMarker.draw(mapMode, mapView, 0xffffffff); + } + } + + public void drawMarkersWorld(float partialTicks) + { + if (!Config.drawMarkersInWorld && !Config.drawMarkersNameInWorld) + { + return; + } + + for (Marker m : this.visibleMarkerList) + { + if (m.dimension == Minecraft.getMinecraft().thePlayer.dimension) + { + if (Config.drawMarkersInWorld) + { + drawBeam(m, partialTicks); + } + if (Config.drawMarkersNameInWorld) + { + drawLabel(m); + } + } + } + } + + public void drawBeam(Marker m, float partialTicks) + { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + float f2 = (float) Minecraft.getMinecraft().theWorld.getTotalWorldTime() + partialTicks; + double d3 = (double) f2 * 0.025D * -1.5D; + // the height of the beam always to the max height + double d17 = 255.0D; + + double x = (double) m.x - TileEntityRendererDispatcher.staticPlayerX; + double y = 0.0D - TileEntityRendererDispatcher.staticPlayerY; + double z = (double) m.z - TileEntityRendererDispatcher.staticPlayerZ; + + GlStateManager.pushMatrix(); + GlStateManager.disableTexture2D(); + GlStateManager.disableLighting(); + GlStateManager.disableCull(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.depthMask(false); + + worldrenderer.startDrawingQuads(); + // size of the square from middle to edge + double d4 = 0.2D; + + double d5 = 0.5D + Math.cos(d3 + 2.356194490192345D) * d4; + double d6 = 0.5D + Math.sin(d3 + 2.356194490192345D) * d4; + double d7 = 0.5D + Math.cos(d3 + (Math.PI / 4D)) * d4; + double d8 = 0.5D + Math.sin(d3 + (Math.PI / 4D)) * d4; + double d9 = 0.5D + Math.cos(d3 + 3.9269908169872414D) * d4; + double d10 = 0.5D + Math.sin(d3 + 3.9269908169872414D) * d4; + double d11 = 0.5D + Math.cos(d3 + 5.497787143782138D) * d4; + double d12 = 0.5D + Math.sin(d3 + 5.497787143782138D) * d4; + + worldrenderer.setColorRGBA_I(m.colour, 50); + + worldrenderer.addVertex(x + d5, y + d17, z + d6); + worldrenderer.addVertex(x + d5, y, z + d6); + worldrenderer.addVertex(x + d7, y, z + d8); + worldrenderer.addVertex(x + d7, y + d17, z + d8); + worldrenderer.addVertex(x + d11, y + d17, z + d12); + worldrenderer.addVertex(x + d11, y, z + d12); + worldrenderer.addVertex(x + d9, y, z + d10); + worldrenderer.addVertex(x + d9, y + d17, z + d10); + worldrenderer.addVertex(x + d7, y + d17, z + d8); + worldrenderer.addVertex(x + d7, y, z + d8); + worldrenderer.addVertex(x + d11, y, z + d12); + worldrenderer.addVertex(x + d11, y + d17, z + d12); + worldrenderer.addVertex(x + d9, y + d17, z + d10); + worldrenderer.addVertex(x + d9, y, z + d10); + worldrenderer.addVertex(x + d5, y, z + d6); + worldrenderer.addVertex(x + d5, y + d17, z + d6); + tessellator.draw(); + + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(m.colour, 50); + // size of the square from middle to edge + d4 = 0.5D; + + d5 = 0.5D + Math.sin(d3 + 2.356194490192345D) * d4; + d6 = 0.5D + Math.cos(d3 + 2.356194490192345D) * d4; + d7 = 0.5D + Math.sin(d3 + (Math.PI / 4D)) * d4; + d8 = 0.5D + Math.cos(d3 + (Math.PI / 4D)) * d4; + d9 = 0.5D + Math.sin(d3 + 3.9269908169872414D) * d4; + d10 = 0.5D + Math.cos(d3 + 3.9269908169872414D) * d4; + d11 = 0.5D + Math.sin(d3 + 5.497787143782138D) * d4; + d12 = 0.5D + Math.cos(d3 + 5.497787143782138D) * d4; + + worldrenderer.addVertex(x + d5, y + d17, z + d6); + worldrenderer.addVertex(x + d5, y, z + d6); + worldrenderer.addVertex(x + d7, y, z + d8); + worldrenderer.addVertex(x + d7, y + d17, z + d8); + worldrenderer.addVertex(x + d11, y + d17, z + d12); + worldrenderer.addVertex(x + d11, y, z + d12); + worldrenderer.addVertex(x + d9, y, z + d10); + worldrenderer.addVertex(x + d9, y + d17, z + d10); + worldrenderer.addVertex(x + d7, y + d17, z + d8); + worldrenderer.addVertex(x + d7, y, z + d8); + worldrenderer.addVertex(x + d11, y, z + d12); + worldrenderer.addVertex(x + d11, y + d17, z + d12); + worldrenderer.addVertex(x + d9, y + d17, z + d10); + worldrenderer.addVertex(x + d9, y, z + d10); + worldrenderer.addVertex(x + d5, y, z + d6); + worldrenderer.addVertex(x + d5, y + d17, z + d6); + tessellator.draw(); + + GlStateManager.enableLighting(); + GlStateManager.enableTexture2D(); + GlStateManager.depthMask(true); + GlStateManager.disableBlend(); + GlStateManager.popMatrix(); + } + + public void drawLabel(Marker m) + { + float growFactor = 0.17F; + Minecraft mc = Minecraft.getMinecraft(); + RenderManager renderManager = mc.getRenderManager(); + FontRenderer fontrenderer = mc.fontRendererObj; + + double x = 0.5D + (double) m.x - TileEntityRendererDispatcher.staticPlayerX; + double y = 0.5D + (double) m.y - TileEntityRendererDispatcher.staticPlayerY; + double z = 0.5D + (double) m.z - TileEntityRendererDispatcher.staticPlayerZ; + + double distance = m.getDistanceToMarker(renderManager.livingPlayer); + + String strText = m.name; + String strDistance = " (" + (int)distance + "m)"; + + int strTextWidth = fontrenderer.getStringWidth(strText) / 2; + int strDistanceWidth = fontrenderer.getStringWidth(strDistance) / 2; + int offstet = 9; + + float f = (float) (1.0F + (distance)*growFactor); + float f1 = 0.016666668F * f; + + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + GL11.glNormal3f(0.0F, 1.0F, 0.0F); + GlStateManager.rotate(-renderManager.playerViewY, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(renderManager.playerViewX, 1.0F, 0.0F, 0.0F); + GlStateManager.scale(-f1, -f1, f1); + GlStateManager.disableLighting(); + GlStateManager.depthMask(false); + GlStateManager.disableDepth(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GL11.glEnable(GL_DEPTH_CLAMP); + + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + GlStateManager.disableTexture2D(); + + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(m.colour, 64); + worldrenderer.addVertex((double) (-strTextWidth - 1), (double) (-1), 0.0D); + worldrenderer.addVertex((double) (-strTextWidth - 1), (double) (8), 0.0D); + worldrenderer.addVertex((double) (strTextWidth + 1), (double) (8), 0.0D); + worldrenderer.addVertex((double) (strTextWidth + 1), (double) (-1), 0.0D); + tessellator.draw(); + + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(m.colour, 64); + worldrenderer.addVertex((double) (-strDistanceWidth - 1), (double) (-1 + offstet), 0.0D); + worldrenderer.addVertex((double) (-strDistanceWidth - 1), (double) (8 + offstet), 0.0D); + worldrenderer.addVertex((double) (strDistanceWidth + 1), (double) (8 + offstet), 0.0D); + worldrenderer.addVertex((double) (strDistanceWidth + 1), (double) (-1 + offstet), 0.0D); + tessellator.draw(); + + GlStateManager.enableTexture2D(); + GlStateManager.depthMask(true); + + fontrenderer.drawString(strText, -strTextWidth, 0, -1); + fontrenderer.drawString(strDistance, -strDistanceWidth, offstet, -1); + + GL11.glDisable(GL_DEPTH_CLAMP); + GlStateManager.enableDepth(); + GlStateManager.enableLighting(); + GlStateManager.disableBlend(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.popMatrix(); + } +} diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index fa50c618..48fdbc25 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -48,9 +48,12 @@ mw.config.moreRealisticMap=Enables realistic map mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic mw.config.newMarkerDialog=New Marker Dialog mw.config.newMarkerDialog.tooltip=Enable to use the new marker dialog -mw.config.useFeetHeight=Use feet height -mw.config.useFeetHeight.tooltip=Have cordinates show feet height instead of head height - +mw.config.drawMarkersInWorld=Show markers in world +mw.config.drawMarkersInWorld.tooltip=Makes a light beam visable in the world on the marker location +mw.config.drawMarkersNameInWorld=Show markers names in world +mw.config.drawMarkersNameInWorld.tooltip=Draws a nameplate on the location of the marker in the world +mw.config.drawMarkersDistanceInWorld=Show markers distance in world +mw.config.drawMarkersDistanceInWorld.tooltip=Draws a distance label on the location of the marker in the world #Config Temp mw.config.overlayModeIndex= From 91e8cfd8cc15193406c074a6e7549b129096aa0d Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 01:09:48 +0200 Subject: [PATCH 082/109] formating, removing unused imports, code cleanup --- .../modwarriors/notenoughkeys/api/Api.java | 86 +- .../api/KeyBindingPressedEvent.java | 90 +- .../notenoughkeys/api/package-info.java | 10 +- .../java/mapwriter/BackgroundExecutor.java | 167 ++- src/main/java/mapwriter/BlockColourGen.java | 357 ++--- src/main/java/mapwriter/ChunkManager.java | 338 +++-- src/main/java/mapwriter/CircularHashMap.java | 183 ++- src/main/java/mapwriter/Mw.java | 543 ++++--- .../java/mapwriter/api/IMwChunkOverlay.java | 18 +- .../java/mapwriter/api/IMwDataProvider.java | 31 +- src/main/java/mapwriter/api/MwAPI.java | 103 +- src/main/java/mapwriter/api/package-info.java | 5 +- src/main/java/mapwriter/config/Config.java | 20 +- .../config/ConfigurationHandler.java | 133 +- .../java/mapwriter/config/MapModeConfig.java | 136 +- .../java/mapwriter/config/WorldConfig.java | 150 +- .../mapwriter/config/largeMapModeConfig.java | 28 +- .../mapwriter/config/smallMapModeConfig.java | 68 +- .../java/mapwriter/forge/ClientProxy.java | 123 +- .../java/mapwriter/forge/CommonProxy.java | 17 +- .../java/mapwriter/forge/EventHandler.java | 106 +- src/main/java/mapwriter/forge/MwForge.java | 123 +- .../java/mapwriter/forge/MwKeyHandler.java | 172 +-- src/main/java/mapwriter/gui/ModGuiConfig.java | 265 ++-- .../mapwriter/gui/ModGuiFactoryHandler.java | 14 +- src/main/java/mapwriter/gui/MwGui.java | 771 +++++----- .../mapwriter/gui/MwGuiDimensionDialog.java | 81 +- src/main/java/mapwriter/gui/MwGuiLabel.java | 400 ++--- .../java/mapwriter/gui/MwGuiMarkerDialog.java | 229 +-- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 731 +++++---- .../mapwriter/gui/MwGuiMarkerListOverlay.java | 97 +- src/main/java/mapwriter/gui/MwGuiSlot.java | 1078 +++++++------- .../mapwriter/gui/MwGuiTeleportDialog.java | 85 +- .../java/mapwriter/gui/MwGuiTextDialog.java | 333 +++-- .../gui/ScrollableColorSelector.java | 178 +-- .../java/mapwriter/gui/ScrollableField.java | 87 +- .../java/mapwriter/gui/ScrollableTextBox.java | 505 +++---- src/main/java/mapwriter/map/MapRenderer.java | 286 ++-- src/main/java/mapwriter/map/MapTexture.java | 371 ++--- .../java/mapwriter/map/MapUpdateViewTask.java | 23 +- src/main/java/mapwriter/map/MapView.java | 630 ++++---- .../java/mapwriter/map/MapViewRequest.java | 30 +- src/main/java/mapwriter/map/Marker.java | 76 +- .../java/mapwriter/map/MarkerManager.java | 390 ++--- src/main/java/mapwriter/map/MiniMap.java | 168 ++- src/main/java/mapwriter/map/Trail.java | 94 +- .../mapwriter/map/UndergroundTexture.java | 467 +++--- .../map/mapmode/FullScreenMapMode.java | 21 +- .../mapwriter/map/mapmode/LargeMapMode.java | 21 +- .../java/mapwriter/map/mapmode/MapMode.java | 502 ++++--- .../mapwriter/map/mapmode/SmallMapMode.java | 21 +- .../mapwriter/overlay/OverlayChecker.java | 262 ++-- .../java/mapwriter/overlay/OverlayGrid.java | 247 ++-- .../java/mapwriter/overlay/OverlaySlime.java | 348 +++-- .../java/mapwriter/region/BlockColours.java | 1303 +++++++++-------- .../java/mapwriter/region/ChunkRender.java | 490 ++++--- src/main/java/mapwriter/region/IChunk.java | 6 +- .../java/mapwriter/region/MergeToImage.java | 199 +-- src/main/java/mapwriter/region/MwChunk.java | 956 ++++++------ src/main/java/mapwriter/region/Region.java | 162 +- .../java/mapwriter/region/RegionFile.java | 848 ++++++----- .../mapwriter/region/RegionFileCache.java | 69 +- .../java/mapwriter/region/RegionManager.java | 302 ++-- .../java/mapwriter/region/SurfacePixels.java | 357 +++-- .../tasks/CloseRegionManagerTask.java | 18 +- src/main/java/mapwriter/tasks/MergeTask.java | 93 +- .../mapwriter/tasks/RebuildRegionsTask.java | 76 +- .../java/mapwriter/tasks/SaveChunkTask.java | 16 +- src/main/java/mapwriter/tasks/Task.java | 42 +- .../tasks/UpdateSurfaceChunksTask.java | 53 +- src/main/java/mapwriter/util/Logging.java | 57 +- src/main/java/mapwriter/util/Reference.java | 94 +- src/main/java/mapwriter/util/Render.java | 820 ++++++----- src/main/java/mapwriter/util/Texture.java | 374 ++--- src/main/java/mapwriter/util/Utils.java | 668 +++++---- .../java/mapwriter/util/VersionCheck.java | 163 ++- 76 files changed, 10060 insertions(+), 8924 deletions(-) diff --git a/src/api/java/modwarriors/notenoughkeys/api/Api.java b/src/api/java/modwarriors/notenoughkeys/api/Api.java index 9187f988..13d9995d 100644 --- a/src/api/java/modwarriors/notenoughkeys/api/Api.java +++ b/src/api/java/modwarriors/notenoughkeys/api/Api.java @@ -1,41 +1,47 @@ -package modwarriors.notenoughkeys.api; - -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -/** - * Center of the API. Main api methods can be found in this class. - * - * @author TheTemportalist - */ -@SideOnly(Side.CLIENT) -public class Api { - - /** - * Checks if NotEnoughKeys is loaded in the current environment - * - * @return 'true' if loaded - */ - public static boolean isLoaded() { - return Loader.isModLoaded("notenoughkeys"); - } - - /** - * Registers a mod's keys with NEK - * - * @param modname The NAME of the mod registering the key - * @param keyDescriptions A String[] (Array[String]) of the key descriptions - * as an inherit array. i.e. ("modName", "key.hotbar1", "key.hotbar2") - */ - public static void registerMod(String modname, String... keyDescriptions) { - try { - Class.forName("modwarriors.notenoughkeys.keys.KeyHelper").getMethod( - "registerMod", String.class, String[].class - ).invoke(null, modname, keyDescriptions); - } catch (Exception e) { - e.printStackTrace(); - } - } - +package modwarriors.notenoughkeys.api; + +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Center of the API. Main api methods can be found in this class. + * + * @author TheTemportalist + */ +@SideOnly(Side.CLIENT) +public class Api +{ + + /** + * Checks if NotEnoughKeys is loaded in the current environment + * + * @return 'true' if loaded + */ + public static boolean isLoaded() + { + return Loader.isModLoaded("notenoughkeys"); + } + + /** + * Registers a mod's keys with NEK + * + * @param modname + * The NAME of the mod registering the key + * @param keyDescriptions + * A String[] (Array[String]) of the key descriptions as an + * inherit array. i.e. ("modName", "key.hotbar1", "key.hotbar2") + */ + public static void registerMod(String modname, String... keyDescriptions) + { + try + { + Class.forName("modwarriors.notenoughkeys.keys.KeyHelper").getMethod("registerMod", String.class, String[].class).invoke(null, modname, keyDescriptions); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } \ No newline at end of file diff --git a/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java b/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java index 0d29e824..ffdb129a 100644 --- a/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java +++ b/src/api/java/modwarriors/notenoughkeys/api/KeyBindingPressedEvent.java @@ -1,43 +1,49 @@ -package modwarriors.notenoughkeys.api; - -import net.minecraftforge.fml.common.eventhandler.Cancelable; -import net.minecraftforge.fml.common.eventhandler.Event; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraft.client.settings.KeyBinding; - -/** - * Called when a keybinding is triggered with the passed with valid modifiers - * - * @author TheTemportalist - */ -@SideOnly(Side.CLIENT) -@Cancelable -public class KeyBindingPressedEvent extends Event { - - /** - * The KeyBinding being triggered - */ - public KeyBinding keyBinding = null; - /** - * Tells whether a modifier was required AND was down when triggered - */ - public boolean shiftRequired = false, ctrlRequired = false, altRequired = false; - - /** - * Called with the passed keyBinding and modifiers. - * Subscribe to this event so activate a keybinding when triggered. - * - * @param keyBinding The KeyBinding being triggered. Stores the key's description and keycode - * @param modifiers The modifiers (SHIFT, CTRL, ALT) that determine when a compatible key is pressed - */ - public KeyBindingPressedEvent(KeyBinding keyBinding, boolean[] modifiers) { - super(); - this.keyBinding = keyBinding; - this.shiftRequired = modifiers[0]; - this.ctrlRequired = modifiers[1]; - this.altRequired = modifiers[2]; - - } - +package modwarriors.notenoughkeys.api; + +import net.minecraft.client.settings.KeyBinding; +import net.minecraftforge.fml.common.eventhandler.Cancelable; +import net.minecraftforge.fml.common.eventhandler.Event; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Called when a keybinding is triggered with the passed with valid modifiers + * + * @author TheTemportalist + */ +@SideOnly(Side.CLIENT) +@Cancelable +public class KeyBindingPressedEvent extends Event +{ + + /** + * The KeyBinding being triggered + */ + public KeyBinding keyBinding = null; + /** + * Tells whether a modifier was required AND was down when triggered + */ + public boolean shiftRequired = false, ctrlRequired = false, altRequired = false; + + /** + * Called with the passed keyBinding and modifiers. Subscribe to this event + * so activate a keybinding when triggered. + * + * @param keyBinding + * The KeyBinding being triggered. Stores the key's description + * and keycode + * @param modifiers + * The modifiers (SHIFT, CTRL, ALT) that determine when a + * compatible key is pressed + */ + public KeyBindingPressedEvent(KeyBinding keyBinding, boolean[] modifiers) + { + super(); + this.keyBinding = keyBinding; + this.shiftRequired = modifiers[0]; + this.ctrlRequired = modifiers[1]; + this.altRequired = modifiers[2]; + + } + } \ No newline at end of file diff --git a/src/api/java/modwarriors/notenoughkeys/api/package-info.java b/src/api/java/modwarriors/notenoughkeys/api/package-info.java index e33da954..3dccd2a1 100644 --- a/src/api/java/modwarriors/notenoughkeys/api/package-info.java +++ b/src/api/java/modwarriors/notenoughkeys/api/package-info.java @@ -1,5 +1,5 @@ - -@API(owner = "Not Enough Keys", provides = "API_NEK", - apiVersion = "1.0.0") package modwarriors.notenoughkeys.api; - -import net.minecraftforge.fml.common.API; \ No newline at end of file +@API(owner = "Not Enough Keys", provides = "API_NEK", apiVersion = "1.0.0") +package modwarriors.notenoughkeys.api; + +import net.minecraftforge.fml.common.API; + diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index 428df1fe..ffde2da6 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -14,76 +14,74 @@ import net.minecraft.world.ChunkCoordIntPair; /* -This class handles executing and managing 'tasks'. -A single background thread runs tasks in the sequence they are added (via addTask()). -A linked list FIFO queue of every unfinished task is processed every time the processTaskQueue method is called. -processTaskQueue checks the task at the front of the queue to see if the background thread has processed it. -If it the task is complete processTaskQueue calls the onComplete() method of the task and removes it from the queue. -If it is not complete the task is added to the front of the queue again. -In this way the tasks are always processed sequentially, in the order they were added to the queue. - -Tasks are extensions of the base Task class. -There are two abstract methods which must be overwritten by the extending class. - void run() - Is executed in the background thread when the executor reaches this task. - void onComplete() - Is called by processTaskQueue() when the task is done (after the run method is complete). - This method runs in the main thread so is a good place to copy the results of the run() method. - -The run() method of a task added to the queue is guaranteed to be run before the run() method of the next task -added. Likewise the onComplete() method of the first task is guaranteed to be run before the onComplete() of the second -task. However the run() method of any class added after a Task may be executed before the onComplete() method of -the earlier Task is called. - -e.g. addTask(Task1) - addTask(Task2) - addTask(Task3) - -may run in the order: - Task1.run() - Task2.run() - Task1.onComplete() - Task3.run() - Task2.onComplete() - Task3.onComplete() -*/ - -public class BackgroundExecutor { - + * This class handles executing and managing 'tasks'. A single background thread + * runs tasks in the sequence they are added (via addTask()). A linked list FIFO + * queue of every unfinished task is processed every time the processTaskQueue + * method is called. processTaskQueue checks the task at the front of the queue + * to see if the background thread has processed it. If it the task is complete + * processTaskQueue calls the onComplete() method of the task and removes it + * from the queue. If it is not complete the task is added to the front of the + * queue again. In this way the tasks are always processed sequentially, in the + * order they were added to the queue. + * + * Tasks are extensions of the base Task class. There are two abstract methods + * which must be overwritten by the extending class. void run() Is executed in + * the background thread when the executor reaches this task. void onComplete() + * Is called by processTaskQueue() when the task is done (after the run method + * is complete). This method runs in the main thread so is a good place to copy + * the results of the run() method. + * + * The run() method of a task added to the queue is guaranteed to be run before + * the run() method of the next task added. Likewise the onComplete() method of + * the first task is guaranteed to be run before the onComplete() of the second + * task. However the run() method of any class added after a Task may be + * executed before the onComplete() method of the earlier Task is called. + * + * e.g. addTask(Task1) addTask(Task2) addTask(Task3) + * + * may run in the order: Task1.run() Task2.run() Task1.onComplete() Task3.run() + * Task2.onComplete() Task3.onComplete() + */ + +public class BackgroundExecutor +{ + private ExecutorService executor; private LinkedList taskQueue; - private Map chunksUpdating = new HashMap(); + private Map chunksUpdating = new HashMap(); public boolean closed = false; - - public BackgroundExecutor() { + + public BackgroundExecutor() + { this.executor = Executors.newSingleThreadExecutor(); this.taskQueue = new LinkedList(); } - + // add a task to the queue - public boolean addTask(Task task) { - if (!this.closed) + public boolean addTask(Task task) + { + if (!this.closed) { if (task instanceof UpdateSurfaceChunksTask) { UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); - - if (!chunksUpdating.containsKey(coords)) + + if (!this.chunksUpdating.containsKey(coords)) { Future future = this.executor.submit(task); task.setFuture(future); - this.taskQueue.add(task); - chunksUpdating.put(coords, task); + this.taskQueue.add(task); + this.chunksUpdating.put(coords, task); } else { - UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask)chunksUpdating.get(coords); - if(task2.Running.get() == false) + UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask) this.chunksUpdating.get(coords); + if (task2.Running.get() == false) { - task2.UpdateChunkData(((UpdateSurfaceChunksTask)task).getChunk()); - } - } + task2.UpdateChunkData(((UpdateSurfaceChunksTask) task).getChunk()); + } + } } else { @@ -91,61 +89,78 @@ public boolean addTask(Task task) { task.setFuture(future); this.taskQueue.add(task); } - - } else { + + } + else + { Logging.log("MwExecutor.addTask: error: cannot add task to closed executor"); } return this.closed; } - - // Pop a Task entry from the task queue and check if the task's thread has finished. + + // Pop a Task entry from the task queue and check if the task's thread has + // finished. // If it has completed then call onComplete for the task. // If it has not completed then push the task back on the queue. - public boolean processTaskQueue() { + public boolean processTaskQueue() + { boolean processed = false; Task task = this.taskQueue.poll(); - if (task != null) { - if (task.isDone()) { + if (task != null) + { + if (task.isDone()) + { task.printException(); task.onComplete(); - + if (task instanceof UpdateSurfaceChunksTask) { UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); - - chunksUpdating.remove(coords, updatetask); - + + this.chunksUpdating.remove(coords, updatetask); + } processed = true; - } else { + } + else + { // put entry back on top of queue this.taskQueue.push(task); } } return !processed; } - - public boolean processRemainingTasks(int attempts, int delay) { - while ((this.taskQueue.size() > 0) && (attempts > 0)) { - if (this.processTaskQueue()) { - try { + + public boolean processRemainingTasks(int attempts, int delay) + { + while ((this.taskQueue.size() > 0) && (attempts > 0)) + { + if (this.processTaskQueue()) + { + try + { Thread.sleep(delay); - } catch (Exception e) { + } + catch (Exception e) + { } attempts--; } } return (attempts <= 0); } - - public int tasksRemaining() { + + public int tasksRemaining() + { return this.taskQueue.size(); } - - public boolean close() { + + public boolean close() + { boolean error = true; - try { + try + { // stop accepting new tasks this.executor.shutdown(); // process remaining tasks @@ -153,7 +168,9 @@ public boolean close() { // should already be terminated, but just in case... error = !this.executor.awaitTermination(10L, TimeUnit.SECONDS); error = false; - } catch (InterruptedException e) { + } + catch (InterruptedException e) + { Logging.log("error: IO task was interrupted during shutdown"); e.printStackTrace(); } diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index d668d735..dad1bcdd 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -1,174 +1,183 @@ -package mapwriter; - -import mapwriter.region.BlockColours; -import mapwriter.util.Logging; -import mapwriter.util.Render; -import mapwriter.util.Texture; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.MathHelper; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.ColorizerFoliage; -import net.minecraft.world.ColorizerGrass; -import net.minecraft.world.biome.BiomeGenBase; - -// Static class to generate BlockColours. -// This is separate from BlockColours because it needs to run in the GL rendering thread -// whereas the generated BlockColours object is used only in the background thread. -// So basically split to make it clear that BlockColourGen and the generated BlockColours -// must not have any interaction after it is generated. - -public class BlockColourGen { - - private static int getIconMapColour(TextureAtlasSprite icon, - Texture terrainTexture) { - // flipped icons have the U and V coords reversed (minU > maxU, minV > - // maxV). - // thanks go to taelnia for fixing this. - int iconX = (int) Math.round(((float) terrainTexture.w) - * Math.min(icon.getMinU(), icon.getMaxU())); - int iconY = (int) Math.round(((float) terrainTexture.h) - * Math.min(icon.getMinV(), icon.getMaxV())); - int iconWidth = (int) Math.round(((float) terrainTexture.w) - * Math.abs(icon.getMaxU() - icon.getMinU())); - int iconHeight = (int) Math.round(((float) terrainTexture.h) - * Math.abs(icon.getMaxV() - icon.getMinV())); - - int[] pixels = new int[iconWidth * iconHeight]; - - //MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); - - terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, iconWidth, icon); - - // need to use custom averaging routine rather than scaling down to one pixel to - // stop transparent pixel colours being included in the average. - return Render.getAverageColourOfArray(pixels); - } - - private static void genBiomeColours(BlockColours bc) { - // generate array of foliage, grass, and water colour multipliers - // for each biome. - - for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { - if (BiomeGenBase.getBiomeGenArray()[i] != null) { - bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i] - .getWaterColorMultiplier() & 0xffffff); - - double temp = MathHelper.clamp_float( - BiomeGenBase.getBiomeGenArray()[i].temperature, 0.0F, - 1.0F); - double rain = MathHelper - .clamp_float( - BiomeGenBase.getBiomeGenArray()[i].rainfall, - 0.0F, 1.0F); - int grasscolor = ColorizerGrass.getGrassColor(temp, rain); - int foliagecolor = ColorizerFoliage.getFoliageColor(temp, rain); - - bc.setBiomeGrassShading(i, grasscolor & 0xffffff); - bc.setBiomeFoliageShading(i, foliagecolor & 0xffffff); - } else { - bc.setBiomeWaterShading(i, 0xffffff); - bc.setBiomeGrassShading(i, 0xffffff); - bc.setBiomeFoliageShading(i, 0xffffff); - } - } - } - - public static void genBlockColours(BlockColours bc) { - - Logging.log("generating block map colours from textures"); - - // copy terrain texture to MwRender pixel bytebuffer - - // bind the terrain texture - // Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); - // get the bound texture id - // int terrainTextureId = Render.getBoundTextureId(); - - int terrainTextureId = Minecraft.getMinecraft().renderEngine - .getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); - - // create texture object from the currently bound GL texture - if (terrainTextureId == 0) { - Logging.log("error: could get terrain texture ID"); - return; - } - Texture terrainTexture = new Texture(terrainTextureId); - - double u1Last = 0; - double u2Last = 0; - double v1Last = 0; - double v2Last = 0; - int blockColourLast = 0; - int e_count = 0; - int b_count = 0; - int s_count = 0; - - for (Object oblock : Block.blockRegistry) { - Block block = (Block) oblock; - int blockID = Block.getIdFromBlock(block); - if (blockID == 0) { - continue; - } - for (int dv = 0; dv < 16; dv++) { - - //int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); - int blockColour = 0; - - if (block != null) { - - TextureAtlasSprite icon = null; - try { - icon = Minecraft.getMinecraft() - .getBlockRendererDispatcher() - .getBlockModelShapes() - .getTexture(block.getStateFromMeta(dv)); - } catch (Exception e) { - // MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", - // blockID, dv); - // e.printStackTrace(); - e_count++; - } - - if (icon != null) { - double u1 = icon.getMinU(); - double u2 = icon.getMaxU(); - double v1 = icon.getMinV(); - double v2 = icon.getMaxV(); - - if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) - && (v2 == v2Last)) { - blockColour = blockColourLast; - s_count++; - } else { - blockColour = getIconMapColour(icon, terrainTexture); - //request icon with meta 16, carpenterblocks uses this method to get the real texture - //this makes the carpenterblocks render as brown blocks on the map - if (((ResourceLocation)Block.blockRegistry.getNameForObject(block)).getResourceDomain().contains("CarpentersBlocks")) - { - //icon = block.getIcon(1, 16); - //blockColour = getIconMapColour(icon, terrainTexture); - } - - u1Last = u1; - u2Last = u2; - v1Last = v1; - v2Last = v2; - blockColourLast = blockColour; - b_count++; - } - } - } - bc.setColour(block.delegate.name(), String.valueOf(dv), - blockColour); - } - } - - Logging.log("processed %d block textures, %d skipped, %d exceptions", - b_count, s_count, e_count); - - genBiomeColours(bc); - } -} +package mapwriter; + +import mapwriter.region.BlockColours; +import mapwriter.util.Logging; +import mapwriter.util.Render; +import mapwriter.util.Texture; +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.ColorizerFoliage; +import net.minecraft.world.ColorizerGrass; +import net.minecraft.world.biome.BiomeGenBase; + +// Static class to generate BlockColours. +// This is separate from BlockColours because it needs to run in the GL +// rendering thread +// whereas the generated BlockColours object is used only in the background +// thread. +// So basically split to make it clear that BlockColourGen and the generated +// BlockColours +// must not have any interaction after it is generated. + +public class BlockColourGen +{ + + private static int getIconMapColour(TextureAtlasSprite icon, Texture terrainTexture) + { + // flipped icons have the U and V coords reversed (minU > maxU, minV > + // maxV). + // thanks go to taelnia for fixing this. + int iconX = Math.round((terrainTexture.w) * Math.min(icon.getMinU(), icon.getMaxU())); + int iconY = Math.round((terrainTexture.h) * Math.min(icon.getMinV(), icon.getMaxV())); + int iconWidth = Math.round((terrainTexture.w) * Math.abs(icon.getMaxU() - icon.getMinU())); + int iconHeight = Math.round((terrainTexture.h) * Math.abs(icon.getMaxV() - icon.getMinV())); + + int[] pixels = new int[iconWidth * iconHeight]; + + // MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); + + terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, iconWidth, icon); + + // need to use custom averaging routine rather than scaling down to one + // pixel to + // stop transparent pixel colours being included in the average. + return Render.getAverageColourOfArray(pixels); + } + + private static void genBiomeColours(BlockColours bc) + { + // generate array of foliage, grass, and water colour multipliers + // for each biome. + + for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) + { + if (BiomeGenBase.getBiomeGenArray()[i] != null) + { + bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); + + double temp = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].temperature, 0.0F, 1.0F); + double rain = MathHelper.clamp_float(BiomeGenBase.getBiomeGenArray()[i].rainfall, 0.0F, 1.0F); + int grasscolor = ColorizerGrass.getGrassColor(temp, rain); + int foliagecolor = ColorizerFoliage.getFoliageColor(temp, rain); + + bc.setBiomeGrassShading(i, grasscolor & 0xffffff); + bc.setBiomeFoliageShading(i, foliagecolor & 0xffffff); + } + else + { + bc.setBiomeWaterShading(i, 0xffffff); + bc.setBiomeGrassShading(i, 0xffffff); + bc.setBiomeFoliageShading(i, 0xffffff); + } + } + } + + public static void genBlockColours(BlockColours bc) + { + + Logging.log("generating block map colours from textures"); + + // copy terrain texture to MwRender pixel bytebuffer + + // bind the terrain texture + // Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); + // get the bound texture id + // int terrainTextureId = Render.getBoundTextureId(); + + int terrainTextureId = Minecraft.getMinecraft().renderEngine.getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); + + // create texture object from the currently bound GL texture + if (terrainTextureId == 0) + { + Logging.log("error: could get terrain texture ID"); + return; + } + Texture terrainTexture = new Texture(terrainTextureId); + + double u1Last = 0; + double u2Last = 0; + double v1Last = 0; + double v2Last = 0; + int blockColourLast = 0; + int e_count = 0; + int b_count = 0; + int s_count = 0; + + for (Object oblock : Block.blockRegistry) + { + Block block = (Block) oblock; + int blockID = Block.getIdFromBlock(block); + if (blockID == 0) + { + continue; + } + for (int dv = 0; dv < 16; dv++) + { + + // int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); + int blockColour = 0; + + if (block != null) + { + + TextureAtlasSprite icon = null; + try + { + icon = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(block.getStateFromMeta(dv)); + } + catch (Exception e) + { + // MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", + // blockID, dv); + // e.printStackTrace(); + e_count++; + } + + if (icon != null) + { + double u1 = icon.getMinU(); + double u2 = icon.getMaxU(); + double v1 = icon.getMinV(); + double v2 = icon.getMaxV(); + + if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) && (v2 == v2Last)) + { + blockColour = blockColourLast; + s_count++; + } + else + { + blockColour = getIconMapColour(icon, terrainTexture); + // request icon with meta 16, carpenterblocks uses + // this method to get the real texture + // this makes the carpenterblocks render as brown + // blocks on the map + if (((ResourceLocation) Block.blockRegistry.getNameForObject(block)).getResourceDomain().contains("CarpentersBlocks")) + { + // icon = block.getIcon(1, 16); + // blockColour = getIconMapColour(icon, + // terrainTexture); + } + + u1Last = u1; + u2Last = u2; + v1Last = v1; + v2Last = v2; + blockColourLast = blockColour; + b_count++; + } + } + } + bc.setColour(block.delegate.name(), String.valueOf(dv), blockColour); + } + } + + Logging.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); + + genBiomeColours(bc); + } +} diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java index b338c9b8..9c69d244 100644 --- a/src/main/java/mapwriter/ChunkManager.java +++ b/src/main/java/mapwriter/ChunkManager.java @@ -1,152 +1,188 @@ -package mapwriter; - -import java.util.Arrays; -import java.util.Map; - -import mapwriter.config.Config; -import mapwriter.region.MwChunk; -import mapwriter.tasks.SaveChunkTask; -import mapwriter.tasks.UpdateSurfaceChunksTask; -import mapwriter.util.Utils; -import net.minecraft.client.Minecraft; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockPos; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.storage.ExtendedBlockStorage; - -import com.google.common.collect.Maps; - -public class ChunkManager { - public Mw mw; - private boolean closed = false; - private CircularHashMap chunkMap = new CircularHashMap(); - - private static final int VISIBLE_FLAG = 0x01; - private static final int VIEWED_FLAG = 0x02; - - public ChunkManager(Mw mw) { - this.mw = mw; - } - - public synchronized void close() { - this.closed = true; - this.saveChunks(); - this.chunkMap.clear(); - } - - // create MwChunk from Minecraft chunk. - // only MwChunk's should be used in the background thread. - // make this a full copy of chunk data to prevent possible race conditions <-- done - public static MwChunk copyToMwChunk(Chunk chunk) { - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = Maps.newHashMap(); - TileEntityMap = Utils.checkedMapByCopy(chunk.getTileEntityMap(), BlockPos.class, TileEntity.class, false); - char[][] dataArray = new char[16][]; - - ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); - if (storageArrays != null) { - for (ExtendedBlockStorage storage : storageArrays) { - if (storage != null) { - int y = (storage.getYLocation() >> 4) & 0xf; - dataArray[y] = storage.getData(); - lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; - } - } - } - - return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), - dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(),chunk.getBiomeArray().length),TileEntityMap); - } - - public synchronized void addChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - this.chunkMap.put(chunk, 0); - } - } - - public synchronized void removeChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? - int flags = this.chunkMap.get(chunk); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(chunk); - } - this.chunkMap.remove(chunk); - } - } - - public synchronized void saveChunks() { - for (Map.Entry entry : this.chunkMap.entrySet()) { - int flags = entry.getValue(); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(entry.getKey()); - } - } - } - - public void updateUndergroundChunks() { - int chunkArrayX = (this.mw.playerXInt >> 4) - 1; - int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; - MwChunk[] chunkArray = new MwChunk[9]; - for (int z = 0; z < 3; z++) { - for (int x = 0; x < 3; x++) { - Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( - chunkArrayX + x, - chunkArrayZ + z - ); - if (!chunk.isEmpty()) { - chunkArray[(z * 3) + x] = copyToMwChunk(chunk); - } - } - } - } - - public void updateSurfaceChunks() { - int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); - MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; - for (int i = 0; i < chunksToUpdate; i++) { - Map.Entry entry = this.chunkMap.getNextEntry(); - if (entry != null) { - // if this chunk is within a certain distance to the player then - // add it to the viewed set - Chunk chunk = entry.getKey(); - - int flags = entry.getValue(); - if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) { - flags |= (VISIBLE_FLAG | VIEWED_FLAG); - } else { - flags &= ~VISIBLE_FLAG; - } - entry.setValue(flags); - - if ((flags & VISIBLE_FLAG) != 0) { - chunkArray[i] = copyToMwChunk(chunk); - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray[i])); - } else { - chunkArray[i] = null; - } - } - } - - //this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - public void onTick() { - if (!this.closed) { - if ((this.mw.tickCounter & 0xf) == 0) { - this.updateUndergroundChunks(); - } else { - this.updateSurfaceChunks(); - } - } - } - - private void addSaveChunkTask(Chunk chunk) { - if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || - (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) { - if (!chunk.isEmpty()) { - this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); - } - } - } +package mapwriter; + +import java.util.Arrays; +import java.util.Map; + +import mapwriter.config.Config; +import mapwriter.region.MwChunk; +import mapwriter.tasks.SaveChunkTask; +import mapwriter.tasks.UpdateSurfaceChunksTask; +import mapwriter.util.Utils; +import net.minecraft.client.Minecraft; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +import com.google.common.collect.Maps; + +public class ChunkManager +{ + public Mw mw; + private boolean closed = false; + private CircularHashMap chunkMap = new CircularHashMap(); + + private static final int VISIBLE_FLAG = 0x01; + private static final int VIEWED_FLAG = 0x02; + + public ChunkManager(Mw mw) + { + this.mw = mw; + } + + public synchronized void close() + { + this.closed = true; + this.saveChunks(); + this.chunkMap.clear(); + } + + // create MwChunk from Minecraft chunk. + // only MwChunk's should be used in the background thread. + // make this a full copy of chunk data to prevent possible race conditions + // <-- done + public static MwChunk copyToMwChunk(Chunk chunk) + { + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = Maps.newHashMap(); + TileEntityMap = Utils.checkedMapByCopy(chunk.getTileEntityMap(), BlockPos.class, TileEntity.class, false); + char[][] dataArray = new char[16][]; + + ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); + if (storageArrays != null) + { + for (ExtendedBlockStorage storage : storageArrays) + { + if (storage != null) + { + int y = (storage.getYLocation() >> 4) & 0xf; + dataArray[y] = storage.getData(); + lightingArray[y] = (storage.getBlocklightArray() != null) ? Arrays.copyOf(storage.getBlocklightArray().getData(), storage.getBlocklightArray().getData().length) : null; + } + } + } + + return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.getWorld().provider.getDimensionId(), dataArray, lightingArray, Arrays.copyOf(chunk.getBiomeArray(), chunk.getBiomeArray().length), TileEntityMap); + } + + public synchronized void addChunk(Chunk chunk) + { + if (!this.closed && (chunk != null)) + { + this.chunkMap.put(chunk, 0); + } + } + + public synchronized void removeChunk(Chunk chunk) + { + if (!this.closed && (chunk != null)) + { + if (!this.chunkMap.containsKey(chunk)) + { + return; // FIXME: Is this failsafe enough for unloading? + } + int flags = this.chunkMap.get(chunk); + if ((flags & VIEWED_FLAG) != 0) + { + this.addSaveChunkTask(chunk); + } + this.chunkMap.remove(chunk); + } + } + + public synchronized void saveChunks() + { + for (Map.Entry entry : this.chunkMap.entrySet()) + { + int flags = entry.getValue(); + if ((flags & VIEWED_FLAG) != 0) + { + this.addSaveChunkTask(entry.getKey()); + } + } + } + + public void updateUndergroundChunks() + { + int chunkArrayX = (this.mw.playerXInt >> 4) - 1; + int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; + MwChunk[] chunkArray = new MwChunk[9]; + for (int z = 0; z < 3; z++) + { + for (int x = 0; x < 3; x++) + { + Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords(chunkArrayX + x, chunkArrayZ + z); + if (!chunk.isEmpty()) + { + chunkArray[(z * 3) + x] = copyToMwChunk(chunk); + } + } + } + } + + public void updateSurfaceChunks() + { + int chunksToUpdate = Math.min(this.chunkMap.size(), Config.chunksPerTick); + MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; + for (int i = 0; i < chunksToUpdate; i++) + { + Map.Entry entry = this.chunkMap.getNextEntry(); + if (entry != null) + { + // if this chunk is within a certain distance to the player then + // add it to the viewed set + Chunk chunk = entry.getKey(); + + int flags = entry.getValue(); + if (Utils.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= Config.maxChunkSaveDistSq) + { + flags |= (VISIBLE_FLAG | VIEWED_FLAG); + } + else + { + flags &= ~VISIBLE_FLAG; + } + entry.setValue(flags); + + if ((flags & VISIBLE_FLAG) != 0) + { + chunkArray[i] = copyToMwChunk(chunk); + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray[i])); + } + else + { + chunkArray[i] = null; + } + } + } + + // this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, + // chunkArray)); + } + + public void onTick() + { + if (!this.closed) + { + if ((this.mw.tickCounter & 0xf) == 0) + { + this.updateUndergroundChunks(); + } + else + { + this.updateSurfaceChunks(); + } + } + } + + private void addSaveChunkTask(Chunk chunk) + { + if ((Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledMP) || (!Minecraft.getMinecraft().isSingleplayer() && Config.regionFileOutputEnabledSP)) + { + if (!chunk.isEmpty()) + { + this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + } + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/CircularHashMap.java b/src/main/java/mapwriter/CircularHashMap.java index 30e1c734..2064011d 100644 --- a/src/main/java/mapwriter/CircularHashMap.java +++ b/src/main/java/mapwriter/CircularHashMap.java @@ -6,35 +6,38 @@ import java.util.Map; import java.util.Set; -public class CircularHashMap { - /* A hash map where each node is linked to the previous and next nodes - * in the order of insertion. - * - * The 'head' node is the most recently added node. Its next pointer - * links to the first node added, forming a circle. - * - * The getNextEntry and getPrevEntry methods use an internal pointer to - * the 'current' node, and return either the current nodes 'next' or - * 'prev' node respectively. - * The current node becomes the node that was returned, such that repeated - * calls traverse all nodes in the map. - * - * Most methods are similar to those in the java.util.Map interface. - * The CircularHashMap class does not implement Map however as some of the +public class CircularHashMap +{ + /* + * A hash map where each node is linked to the previous and next nodes in + * the order of insertion. + * + * The 'head' node is the most recently added node. Its next pointer links + * to the first node added, forming a circle. + * + * The getNextEntry and getPrevEntry methods use an internal pointer to the + * 'current' node, and return either the current nodes 'next' or 'prev' node + * respectively. The current node becomes the node that was returned, such + * that repeated calls traverse all nodes in the map. + * + * Most methods are similar to those in the java.util.Map interface. The + * CircularHashMap class does not implement Map however as some of the * required methods seemed unnecessary. */ - + private Map nodeMap = new HashMap(); private Node headNode = null; private Node currentNode = null; - - public class Node implements Map.Entry{ + + public class Node implements Map.Entry + { private final K key; private V value; private Node next; private Node prev; - - Node(K key, V value) { + + Node(K key, V value) + { this.key = key; this.value = value; this.next = this; @@ -42,85 +45,104 @@ public class Node implements Map.Entry{ } @Override - public K getKey() { + public K getKey() + { return this.key; } @Override - public V getValue() { + public V getValue() + { return this.value; } @Override - public V setValue(V value) { + public V setValue(V value) + { V oldValue = this.value; this.value = value; return oldValue; } } - - public V put(K key, V value) { + + public V put(K key, V value) + { Node node = this.nodeMap.get(key); - if (node == null) { + if (node == null) + { // add new node node = new Node(key, value); this.nodeMap.put(key, node); - - if (this.headNode == null) { + + if (this.headNode == null) + { node.next = node; node.prev = node; - - } else { + + } + else + { node.next = this.headNode.next; node.prev = this.headNode; - + this.headNode.next.prev = node; this.headNode.next = node; } - - if (this.currentNode == null) { + + if (this.currentNode == null) + { this.currentNode = node; } - + this.headNode = node; - - } else { + + } + else + { // update node node.value = value; } return value; } - - public V remove(Object key) { + + public V remove(Object key) + { Node node = this.nodeMap.get(key); V value = null; - if (node != null) { - if (this.headNode == node) { + if (node != null) + { + if (this.headNode == node) + { this.headNode = node.next; - if (this.headNode == node) { + if (this.headNode == node) + { this.headNode = null; } } - if (this.currentNode == node) { + if (this.currentNode == node) + { this.currentNode = node.next; - if (this.currentNode == node) { + if (this.currentNode == node) + { this.currentNode = null; } } - + node.prev.next = node.next; node.next.prev = node.prev; node.next = null; node.prev = null; value = node.value; - + this.nodeMap.remove(key); } return value; } - - public void clear() { - for (Node node : this.nodeMap.values()) { + + public void clear() + { + for (Node node : this.nodeMap.values()) + { node.next = null; node.prev = null; } @@ -128,65 +150,80 @@ public void clear() { this.headNode = null; this.currentNode = null; } - - public boolean containsKey(Object key) { + + public boolean containsKey(Object key) + { return this.nodeMap.containsKey(key); } - - public int size() { + + public int size() + { return this.nodeMap.size(); } - - public Set keySet() { + + public Set keySet() + { return this.nodeMap.keySet(); } - - public Collection values() { + + public Collection values() + { Collection list = new ArrayList(); - for (Node node : this.nodeMap.values()) { + for (Node node : this.nodeMap.values()) + { list.add(node.value); } return list; } - public Collection> entrySet() { + public Collection> entrySet() + { return new ArrayList>(this.nodeMap.values()); } - - public V get(Object key) { + + public V get(Object key) + { Node node = this.nodeMap.get(key); return (node != null) ? node.value : null; } - public boolean isEmpty() { + public boolean isEmpty() + { return this.nodeMap.isEmpty(); } - + // // interface to traverse circular nodes // - - public Map.Entry getNextEntry() { - if (this.currentNode != null) { + + public Map.Entry getNextEntry() + { + if (this.currentNode != null) + { this.currentNode = this.currentNode.next; } return this.currentNode; } - - public Map.Entry getPrevEntry() { - if (this.currentNode != null) { + + public Map.Entry getPrevEntry() + { + if (this.currentNode != null) + { this.currentNode = this.currentNode.prev; } return this.currentNode; } - - public void rewind() { + + public void rewind() + { this.currentNode = (this.headNode != null) ? this.headNode.next : null; } - - public boolean setPosition(K key) { + + public boolean setPosition(K key) + { Node node = this.nodeMap.get(key); - if (node != null) { + if (node != null) + { this.currentNode = node; } return (node != null); diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 33d62dd0..e63d77b2 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -1,7 +1,7 @@ package mapwriter; import java.io.File; - + import mapwriter.config.Config; import mapwriter.config.ConfigurationHandler; import mapwriter.config.WorldConfig; @@ -9,7 +9,7 @@ import mapwriter.forge.MwKeyHandler; import mapwriter.gui.MwGui; import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.gui.MwGuiMarkerDialogNew; +import mapwriter.gui.MwGuiMarkerDialogNew; import mapwriter.map.MapTexture; import mapwriter.map.MapView; import mapwriter.map.Marker; @@ -31,22 +31,23 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; -public class Mw { +public class Mw +{ public Minecraft mc = null; - + // directories private final File configDir; private final File saveDir; public File worldDir = null; public File imageDir = null; - + // flags and counters public boolean ready = false; - //public boolean multiplayer = false; + // public boolean multiplayer = false; public int tickCounter = 0; - + public int textureSize = 2048; - + // player position and heading public double playerX = 0.0; public double playerZ = 0.0; @@ -57,7 +58,7 @@ public class Mw { public double playerHeading = 0.0; public int playerDimension = 0; public float mapRotationDegrees = 0.0f; - + // instances of components public MapTexture mapTexture = null; public UndergroundTexture undergroundMapTexture = null; @@ -68,157 +69,200 @@ public class Mw { public RegionManager regionManager = null; public ChunkManager chunkManager = null; public Trail playerTrail = null; - + private static Mw instance; - - public static Mw getInstance() { - if (instance == null ) { - synchronized (WorldConfig.class) { - if (instance == null) { - instance = new Mw(); - } - } - } - - return instance; - } - - private Mw() { + + public static Mw getInstance() + { + if (instance == null) + { + synchronized (WorldConfig.class) + { + if (instance == null) + { + instance = new Mw(); + } + } + } + + return instance; + } + + private Mw() + { // client only initialization this.mc = Minecraft.getMinecraft(); - + // create base save directory this.saveDir = new File(this.mc.mcDataDir, "saves"); this.configDir = new File(this.mc.mcDataDir, "config"); - + this.ready = false; - + RegionManager.logger = MwForge.logger; - + ConfigurationHandler.loadConfig(); } - - public void setTextureSize() { - if (Config.configTextureSize != this.textureSize) { + + public void setTextureSize() + { + if (Config.configTextureSize != this.textureSize) + { int maxTextureSize = Render.getMaxTextureSize(); int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) { + while ((textureSize <= maxTextureSize) && (textureSize <= Config.configTextureSize)) + { textureSize *= 2; } textureSize /= 2; - + Logging.log("GL reported max texture size = %d", maxTextureSize); Logging.log("texture size from config = %d", Config.configTextureSize); Logging.log("setting map texture size to = %d", textureSize); - + this.textureSize = textureSize; - if (this.ready) { - // if we are already up and running need to close and reinitialize the map texture and + if (this.ready) + { + // if we are already up and running need to close and + // reinitialize the map texture and // region manager. this.reloadMapTexture(); } } } - + // update the saved player position and orientation // called every tick - public void updatePlayer() { + public void updatePlayer() + { // get player pos - this.playerX = (double) this.mc.thePlayer.posX; - this.playerY = (double) this.mc.thePlayer.posY; - this.playerZ = (double) this.mc.thePlayer.posZ; + this.playerX = this.mc.thePlayer.posX; + this.playerY = this.mc.thePlayer.posY; + this.playerZ = this.mc.thePlayer.posZ; this.playerXInt = (int) Math.floor(this.playerX); this.playerYInt = (int) Math.floor(this.playerY); this.playerZInt = (int) Math.floor(this.playerZ); - - // rotationYaw of 0 points due north, we want it to point due east instead + + // rotationYaw of 0 points due north, we want it to point due east + // instead // so add pi/2 radians (90 degrees) this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; - + // set by onWorldLoad this.playerDimension = this.mc.theWorld.provider.getDimensionId(); if (this.miniMap.view.getDimension() != this.playerDimension) { - WorldConfig.getInstance().addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); + WorldConfig.getInstance().addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); } } - - public void toggleMarkerMode() { + + public void toggleMarkerMode() + { this.markerManager.nextGroup(); this.markerManager.update(); this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); } - + // cheap and lazy way to teleport... - public void teleportTo(int x, int y, int z) { - if (Config.teleportEnabled) { + public void teleportTo(int x, int y, int z) + { + if (Config.teleportEnabled) + { this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", Config.teleportCommand, x, y, z)); - } else { + } + else + { Utils.printBoth("teleportation is disabled in mapwriter.cfg"); } } - - public void warpTo(String name) { - if (Config.teleportEnabled) { - //MwUtil.printBoth(String.format("warping to %s", name)); + + public void warpTo(String name) + { + if (Config.teleportEnabled) + { + // MwUtil.printBoth(String.format("warping to %s", name)); this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); - } else { + } + else + { Utils.printBoth("teleportation is disabled in mapwriter.cfg"); } } - - public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!Config.teleportCommand.equals("warp")) { + + public void teleportToMapPos(MapView mapView, int x, int y, int z) + { + if (!Config.teleportCommand.equals("warp")) + { double scale = mapView.getDimensionScaling(this.playerDimension); this.teleportTo((int) (x / scale), y, (int) (z / scale)); - } else { + } + else + { Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); } } - - public void teleportToMarker(Marker marker) { - if (Config.teleportCommand.equals("warp")) { + + public void teleportToMarker(Marker marker) + { + if (Config.teleportCommand.equals("warp")) + { this.warpTo(marker.name); - } else if (marker.dimension == this.playerDimension) { + } + else if (marker.dimension == this.playerDimension) + { this.teleportTo(marker.x, marker.y, marker.z); - } else { + } + else + { Utils.printBoth("cannot teleport to marker in different dimension"); } } - - public void loadBlockColourOverrides(BlockColours bc) { + + public void loadBlockColourOverrides(BlockColours bc) + { File f = new File(this.configDir, Reference.blockColourOverridesFileName); - if (f.isFile()) { + if (f.isFile()) + { Logging.logInfo("loading block colour overrides file %s", f); bc.loadFromFile(f); - } else { + } + else + { Logging.logInfo("recreating block colour overrides file %s", f); BlockColours.writeOverridesFile(f); - if (f.isFile()) { + if (f.isFile()) + { bc.loadFromFile(f); - } else { + } + else + { Logging.logError("could not load block colour overrides from file %s", f); } } } - - public void saveBlockColours(BlockColours bc) { + + public void saveBlockColours(BlockColours bc) + { File f = new File(this.configDir, Reference.blockColourSaveFileName); Logging.logInfo("saving block colours to '%s'", f); bc.saveToFile(f); } - - public void reloadBlockColours() { + + public void reloadBlockColours() + { BlockColours bc = new BlockColours(); File f = new File(this.configDir, Reference.blockColourSaveFileName); - if (Config.useSavedBlockColours && f.isFile()) { + if (Config.useSavedBlockColours && f.isFile()) + { // load block colours from file Logging.logInfo("loading block colours from %s", f); bc.loadFromFile(f); this.loadBlockColourOverrides(bc); - } else { + } + else + { // generate block colours from current texture pack Logging.logInfo("generating block colours"); BlockColourGen.genBlockColours(bc); @@ -228,307 +272,338 @@ public void reloadBlockColours() { } this.blockColours = bc; } - - public void reloadMapTexture() { + + public void reloadMapTexture() + { this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); this.executor.close(); MapTexture oldMapTexture = this.mapTexture; MapTexture newMapTexture = new MapTexture(this.textureSize, Config.linearTextureScaling); this.mapTexture = newMapTexture; - if (oldMapTexture != null) { + if (oldMapTexture != null) + { oldMapTexture.close(); } this.executor = new BackgroundExecutor(); this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); - + UndergroundTexture oldTexture = this.undergroundMapTexture; UndergroundTexture newTexture = new UndergroundTexture(this, this.textureSize, Config.linearTextureScaling); this.undergroundMapTexture = newTexture; - if (oldTexture != null) { + if (oldTexture != null) + { this.undergroundMapTexture.close(); } } - - public void toggleUndergroundMode() { + + public void toggleUndergroundMode() + { Config.undergroundMode = !Config.undergroundMode; this.miniMap.view.setUndergroundMode(Config.undergroundMode); } - - //////////////////////////////// + + // ////////////////////////////// // Initialization and Cleanup - //////////////////////////////// - - public void load() { - - if (this.ready) { + // ////////////////////////////// + + public void load() + { + + if (this.ready) + { return; } - - if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { + + if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) + { Logging.log("Mw.load: world or player is null, cannot load yet"); return; } - + Logging.log("Mw.load: loading..."); - + // get world and image directories File saveDir = this.saveDir; - if (Config.saveDirOverride.length() > 0) { + if (Config.saveDirOverride.length() > 0) + { File d = new File(Config.saveDirOverride); - if (d.isDirectory()) { + if (d.isDirectory()) + { saveDir = d; - } else { + } + else + { Logging.log("error: no such directory %s", Config.saveDirOverride); } } - - if (!this.mc.isSingleplayer()) { + + if (!this.mc.isSingleplayer()) + { this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), Utils.getWorldName()); - } else { + } + else + { this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), Utils.getWorldName()); } - + // create directories this.imageDir = new File(this.worldDir, "images"); - if (!this.imageDir.exists()) { + if (!this.imageDir.exists()) + { this.imageDir.mkdirs(); } - if (!this.imageDir.isDirectory()) { + if (!this.imageDir.isDirectory()) + { Logging.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); } - + this.tickCounter = 0; - - //this.multiplayer = !this.mc.isIntegratedServerRunning(); - + + // this.multiplayer = !this.mc.isIntegratedServerRunning(); + // marker manager only depends on the config being loaded this.markerManager = new MarkerManager(); this.markerManager.load(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); - + this.playerTrail = new Trail(this, Reference.PlayerTrailName); - + // executor does not depend on anything this.executor = new BackgroundExecutor(); - + // mapTexture depends on config being loaded this.mapTexture = new MapTexture(this.textureSize, Config.linearTextureScaling); this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, Config.linearTextureScaling); - //this.reloadBlockColours(); + // this.reloadBlockColours(); // region manager depends on config, mapTexture, and block colours this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, Config.zoomInLevels, Config.zoomOutLevels); // overlay manager depends on mapTexture this.miniMap = new MiniMap(this); this.miniMap.view.setDimension(this.mc.thePlayer.dimension); - + this.chunkManager = new ChunkManager(this); - + this.ready = true; - - //if (!zoomLevelsExist) { - //printBoth("recreating zoom levels"); - //this.regionManager.recreateAllZoomLevels(); - //} + + // if (!zoomLevelsExist) { + // printBoth("recreating zoom levels"); + // this.regionManager.recreateAllZoomLevels(); + // } } - - public void close() { - + + public void close() + { + Logging.log("Mw.close: closing..."); - - if (this.ready) { + + if (this.ready) + { this.ready = false; - + this.chunkManager.close(); this.chunkManager = null; - + // close all loaded regions, saving modified images. // this will create extra tasks that need to be completed. this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); this.regionManager = null; - + Logging.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); - if (this.executor.close()) { + if (this.executor.close()) + { Logging.log("error: timeout waiting for tasks to finish"); } Logging.log("done"); - + this.playerTrail.close(); - + this.markerManager.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); this.markerManager.clear(); - + // close overlay this.miniMap.close(); this.miniMap = null; - + this.undergroundMapTexture.close(); this.mapTexture.close(); - + WorldConfig.getInstance().saveWorldConfig(); - //this.saveConfig(); - + // this.saveConfig(); + this.tickCounter = 0; - OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in - } + OverlaySlime.reset(); // Reset the state so the seed will be asked + // again when we log in + } } - - //////////////////////////////// + + // ////////////////////////////// // Event handlers - //////////////////////////////// - - public void onTick() { + // ////////////////////////////// + + public void onTick() + { this.load(); - if (this.ready && (this.mc.thePlayer != null)) { - - setTextureSize(); - + if (this.ready && (this.mc.thePlayer != null)) + { + + this.setTextureSize(); + this.updatePlayer(); - - if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) { + + if (Config.undergroundMode && ((this.tickCounter % 30) == 0)) + { this.undergroundMapTexture.update(); } - if (!(this.mc.currentScreen instanceof MwGui)) { - // if in game (no gui screen) center the minimap on the player and render it. - this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); + if (!(this.mc.currentScreen instanceof MwGui)) + { + // if in game (no gui screen) center the minimap on the player + // and render it. + this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); this.miniMap.drawCurrentMap(); } - + // process background tasks int maxTasks = 50; - while (!this.executor.processTaskQueue() && (maxTasks > 0)) { + while (!this.executor.processTaskQueue() && (maxTasks > 0)) + { maxTasks--; } - + this.chunkManager.onTick(); - + // update GL texture of mapTexture if updated this.mapTexture.processTextureUpdates(); - + // let the renderEngine know we have changed the bound texture. - //this.mc.renderEngine.resetBoundTexture(); - - //if (this.tickCounter % 100 == 0) { - // MwUtil.log("tick %d", this.tickCounter); - //} - this.playerTrail.onTick(); - + // this.mc.renderEngine.resetBoundTexture(); + + // if (this.tickCounter % 100 == 0) { + // MwUtil.log("tick %d", this.tickCounter); + // } + this.playerTrail.onTick(); + this.tickCounter++; } } - + // add chunk to the set of loaded chunks - public void onChunkLoad(Chunk chunk) { + public void onChunkLoad(Chunk chunk) + { this.load(); - if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { - if (this.ready) { + if ((chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) + { + if (this.ready) + { this.chunkManager.addChunk(chunk); - } else { + } + else + { Logging.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); } } } - + // remove chunk from the set of loaded chunks. // convert to mwchunk and write chunk to region file if in multiplayer. - public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) { + public void onChunkUnload(Chunk chunk) + { + if (this.ready && (chunk != null) && (chunk.getWorld() instanceof net.minecraft.client.multiplayer.WorldClient)) + { this.chunkManager.removeChunk(chunk); } } - + // from onTick when mc.currentScreen is an instance of GuiGameOver // it's the only option to detect death client side - public void onPlayerDeath(EntityPlayerMP player) { - if (this.ready && (Config.maxDeathMarkers > 0)) { + public void onPlayerDeath(EntityPlayerMP player) + { + if (this.ready && (Config.maxDeathMarkers > 0)) + { this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers + 1; - for (int i = 0; i < deleteCount; i++) { + int deleteCount = (this.markerManager.countMarkersInGroup("playerDeaths") - Config.maxDeathMarkers) + 1; + for (int i = 0; i < deleteCount; i++) + { // delete the first marker found in the group "playerDeaths". - // as new markers are only ever appended to the marker list this will delete the + // as new markers are only ever appended to the marker list this + // will delete the // earliest death marker added. this.markerManager.delMarker(null, "playerDeaths"); } - + this.markerManager.addMarker(Utils.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); this.markerManager.setVisibleGroupName("playerDeaths"); this.markerManager.update(); } } - - public void onKeyDown(KeyBinding kb) { + + public void onKeyDown(KeyBinding kb) + { // make sure not in GUI element (e.g. chat box) - if ((this.mc.currentScreen == null) && (this.ready)) { - //Mw.log("client tick: %s key pressed", kb.keyDescription); - - if (kb == MwKeyHandler.keyMapMode) { + if ((this.mc.currentScreen == null) && (this.ready)) + { + // Mw.log("client tick: %s key pressed", kb.keyDescription); + + if (kb == MwKeyHandler.keyMapMode) + { // map mode toggle this.miniMap.nextOverlayMode(1); - - } else if (kb == MwKeyHandler.keyMapGui) { + + } + else if (kb == MwKeyHandler.keyMapGui) + { // open map gui this.mc.displayGuiScreen(new MwGui(this)); - - } else if (kb == MwKeyHandler.keyNewMarker) { + + } + else if (kb == MwKeyHandler.keyNewMarker) + { // open new marker dialog String group = this.markerManager.getVisibleGroupName(); - if (group.equals("none")) { + if (group.equals("none")) + { group = "group"; - } - if (Config.newMarkerDialog) - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialogNew( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - } - else - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - } - } else if (kb == MwKeyHandler.keyNextGroup) { + } + if (Config.newMarkerDialog) + { + this.mc.displayGuiScreen(new MwGuiMarkerDialogNew(null, this.markerManager, "", group, this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension)); + } + else + { + this.mc.displayGuiScreen(new MwGuiMarkerDialog(null, this.markerManager, "", group, this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension)); + } + } + else if (kb == MwKeyHandler.keyNextGroup) + { // toggle marker mode this.markerManager.nextGroup(); this.markerManager.update(); this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - - } else if (kb == MwKeyHandler.keyTeleport) { + + } + else if (kb == MwKeyHandler.keyTeleport) + { // set or remove marker - Marker marker = this.markerManager.getNearestMarkerInDirection( - this.playerXInt, - this.playerZInt, - this.playerHeading); - if (marker != null) { - this.teleportToMarker(marker); + Marker marker = this.markerManager.getNearestMarkerInDirection(this.playerXInt, this.playerZInt, this.playerHeading); + if (marker != null) + { + this.teleportToMarker(marker); } - } else if (kb == MwKeyHandler.keyZoomIn) { + } + else if (kb == MwKeyHandler.keyZoomIn) + { // zoom in this.miniMap.view.adjustZoomLevel(-1); - } else if (kb == MwKeyHandler.keyZoomOut) { + } + else if (kb == MwKeyHandler.keyZoomOut) + { // zoom out this.miniMap.view.adjustZoomLevel(1); - } else if (kb == MwKeyHandler.keyUndergroundMode) { + } + else if (kb == MwKeyHandler.keyUndergroundMode) + { this.toggleUndergroundMode(); } } } -} +} diff --git a/src/main/java/mapwriter/api/IMwChunkOverlay.java b/src/main/java/mapwriter/api/IMwChunkOverlay.java index 4fa51d8f..679af750 100644 --- a/src/main/java/mapwriter/api/IMwChunkOverlay.java +++ b/src/main/java/mapwriter/api/IMwChunkOverlay.java @@ -2,11 +2,17 @@ import java.awt.Point; -public interface IMwChunkOverlay { - public Point getCoordinates(); - public int getColor(); - public float getFilling(); +public interface IMwChunkOverlay +{ + public Point getCoordinates(); + + public int getColor(); + + public float getFilling(); + public boolean hasBorder(); - public float getBorderWidth(); - public int getBorderColor(); + + public float getBorderWidth(); + + public int getBorderColor(); } diff --git a/src/main/java/mapwriter/api/IMwDataProvider.java b/src/main/java/mapwriter/api/IMwDataProvider.java index 5ff9505d..8b37b0f1 100644 --- a/src/main/java/mapwriter/api/IMwDataProvider.java +++ b/src/main/java/mapwriter/api/IMwDataProvider.java @@ -5,27 +5,28 @@ import mapwriter.map.MapView; import mapwriter.map.mapmode.MapMode; -public interface IMwDataProvider { +public interface IMwDataProvider +{ public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ); - - //Returns what should be added to the status bar by the addon. + + // Returns what should be added to the status bar by the addon. public String getStatusString(int dim, int bX, int bY, int bZ); - - //Call back for middle click. - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview); - - //Callback for dimension change on the map + + // Call back for middle click. + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview); + + // Callback for dimension change on the map public void onDimensionChanged(int dimension, MapView mapview); - + public void onMapCenterChanged(double vX, double vZ, MapView mapview); - - public void onZoomChanged(int level, MapView mapview); - + + public void onZoomChanged(int level, MapView mapview); + public void onOverlayActivated(MapView mapview); - public void onOverlayDeactivated(MapView mapview); - + public void onOverlayDeactivated(MapView mapview); + public void onDraw(MapView mapview, MapMode mapmode); - + public boolean onMouseInput(MapView mapview, MapMode mapmode); } diff --git a/src/main/java/mapwriter/api/MwAPI.java b/src/main/java/mapwriter/api/MwAPI.java index 01efc6df..5a75616a 100644 --- a/src/main/java/mapwriter/api/MwAPI.java +++ b/src/main/java/mapwriter/api/MwAPI.java @@ -5,81 +5,112 @@ import com.google.common.collect.HashBiMap; -public class MwAPI { +public class MwAPI +{ private static HashBiMap dataProviders = HashBiMap.create(); private static IMwDataProvider currentProvider = null; private static ArrayList providerKeys = new ArrayList(); - - public static void registerDataProvider(String name, IMwDataProvider handler){ + + public static void registerDataProvider(String name, IMwDataProvider handler) + { dataProviders.put(name, handler); providerKeys.add(name); } - - public static Collection getDataProviders(){ + + public static Collection getDataProviders() + { return dataProviders.values(); } - + // Returns the data provider based on its name // - public static IMwDataProvider getDataProvider(String name){ + public static IMwDataProvider getDataProvider(String name) + { return dataProviders.get(name); } // Returns the name based on the data provider // - public static String getProviderName(IMwDataProvider provider){ + public static String getProviderName(IMwDataProvider provider) + { return dataProviders.inverse().get(provider); - } - - public static IMwDataProvider getCurrentDataProvider(){ + } + + public static IMwDataProvider getCurrentDataProvider() + { return currentProvider; } - public static String getCurrentProviderName(){ + public static String getCurrentProviderName() + { if (currentProvider != null) + { return getProviderName(currentProvider); + } else + { return "None"; + } } - - public static IMwDataProvider setCurrentDataProvider(String name){ - currentProvider = dataProviders.get(name); - return currentProvider; + + public static IMwDataProvider setCurrentDataProvider(String name) + { + currentProvider = dataProviders.get(name); + return currentProvider; } - - public static IMwDataProvider setCurrentDataProvider(IMwDataProvider provider){ + + public static IMwDataProvider setCurrentDataProvider(IMwDataProvider provider) + { currentProvider = provider; - return currentProvider; + return currentProvider; } - - public static IMwDataProvider setNextProvider(){ - if (currentProvider != null){ - int index = providerKeys.indexOf(getCurrentProviderName()); - if (index + 1 >= providerKeys.size()){ + + public static IMwDataProvider setNextProvider() + { + if (currentProvider != null) + { + int index = providerKeys.indexOf(getCurrentProviderName()); + if ((index + 1) >= providerKeys.size()) + { currentProvider = null; - } else { - String nextKey = providerKeys.get(index + 1); + } + else + { + String nextKey = providerKeys.get(index + 1); currentProvider = getDataProvider(nextKey); } - } else { + } + else + { if (providerKeys.size() > 0) + { currentProvider = getDataProvider(providerKeys.get(0)); + } } return currentProvider; } - - public static IMwDataProvider setPrevProvider(){ - if (currentProvider != null){ - int index = providerKeys.indexOf(getCurrentProviderName()); - if (index - 1 < 0){ + + public static IMwDataProvider setPrevProvider() + { + if (currentProvider != null) + { + int index = providerKeys.indexOf(getCurrentProviderName()); + if ((index - 1) < 0) + { currentProvider = null; - } else { - String prevKey = providerKeys.get(index - 1); + } + else + { + String prevKey = providerKeys.get(index - 1); currentProvider = getDataProvider(prevKey); } - } else { + } + else + { if (providerKeys.size() > 0) + { currentProvider = getDataProvider(providerKeys.get(providerKeys.size() - 1)); + } } return currentProvider; - } + } } diff --git a/src/main/java/mapwriter/api/package-info.java b/src/main/java/mapwriter/api/package-info.java index f7a37dd7..9ad9f454 100644 --- a/src/main/java/mapwriter/api/package-info.java +++ b/src/main/java/mapwriter/api/package-info.java @@ -1,6 +1,5 @@ - -@API(owner = "MapWriter", provides = "MapWriterApi", - apiVersion = "1.0.0") package mapwriter.api; +@API(owner = "MapWriter", provides = "MapWriterApi", apiVersion = "1.0.0") +package mapwriter.api; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index e7412677..615e37b3 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -2,13 +2,15 @@ import mapwriter.util.Reference; -public class Config { - public static final String[] backgroundModeStringArray = { +public class Config +{ + public static final String[] backgroundModeStringArray = + { "none", "static", "panning" - }; - + }; + // configuration options public static boolean linearTextureScalingDef = true; public static boolean linearTextureScaling = linearTextureScalingDef; @@ -56,16 +58,16 @@ public class Config { public static boolean drawMarkersNameInWorld = drawMarkersNameInWorldDef; public static boolean drawMarkersDistanceInWorldDef = false; public static boolean drawMarkersDistanceInWorld = drawMarkersDistanceInWorldDef; - - //World configuration Options + + // World configuration Options public static int overlayModeIndexDef = 0; public static int overlayModeIndex = overlayModeIndexDef; public static int overlayZoomLevelDef = 0; public static int overlayZoomLevel = overlayZoomLevelDef; public static int fullScreenZoomLevelDef = 0; public static int fullScreenZoomLevel = fullScreenZoomLevelDef; - + public static largeMapModeConfig largeMap = new largeMapModeConfig(Reference.catLargeMapConfig); - public static smallMapModeConfig smallMap = new smallMapModeConfig(Reference.catSmallMapConfig); - public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); + public static smallMapModeConfig smallMap = new smallMapModeConfig(Reference.catSmallMapConfig); + public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); } diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 5f46bfe5..e76a0181 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -7,77 +7,76 @@ import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - public class ConfigurationHandler +public class ConfigurationHandler +{ + // configuration files (global and world specific) + public static Configuration configuration; + + public static void init(File configFile) { - // configuration files (global and world specific) - public static Configuration configuration; + // Create the configuration object from the given configuration file + if (configuration == null) + { + configuration = new Configuration(configFile); + setMapModeDefaults(); + loadConfig(); + } + } + + public static void loadConfig() + { + Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingDef, "mw.config.linearTextureScaling"); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColoursDef, "mw.config.useSavedBlockColours"); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabledDef, "mw.config.teleportEnabled"); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommandDef, "mw.config.teleportCommand"); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSqDef, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabledDef, "mw.config.mapPixelSnapEnabled"); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkersDef, 0, 1000, "mw.config.maxDeathMarkers"); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTickDef, 1, 500, "mw.config.chunksPerTick"); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverrideDef, "mw.config.saveDirOverride"); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabledDef, "mw.config.portNumberInWorldNameEnabled"); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); + Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureMode", Config.backgroundModeStringArray); + Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); + Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); + + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "mw.config.textureSize"); + + Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "mw.config.overlayModeIndex"); + Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); - public static void init(File configFile) - { - // Create the configuration object from the given configuration file - if (configuration == null) - { - configuration = new Configuration(configFile); - setMapModeDefaults(); - loadConfig(); - } - } + Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); - public static void loadConfig() + Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "mw.config.newMarkerDialog"); + Config.drawMarkersInWorld = configuration.getBoolean("drawMarkersInWorld", Reference.catOptions, Config.drawMarkersInWorldDef, "mw.config.drawMarkersInWorld"); + Config.drawMarkersNameInWorld = configuration.getBoolean("drawMarkersNameInWorld", Reference.catOptions, Config.drawMarkersNameInWorldDef, "mw.config.drawMarkersNameInWorld"); + Config.drawMarkersDistanceInWorld = configuration.getBoolean("drawMarkersDistanceInWorld", Reference.catOptions, Config.drawMarkersDistanceInWorldDef, "mw.config.drawMarkersDistanceInWorld"); + + Config.fullScreenMap.loadConfig(); + Config.largeMap.loadConfig(); + Config.smallMap.loadConfig(); + + if (configuration.hasChanged()) { - Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingDef, "mw.config.linearTextureScaling"); - Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColoursDef, "mw.config.useSavedBlockColours"); - Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabledDef, "mw.config.teleportEnabled"); - Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommandDef, "mw.config.teleportCommand"); - Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSqDef, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); - Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabledDef, "mw.config.mapPixelSnapEnabled"); - Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkersDef, 0, 1000, "mw.config.maxDeathMarkers"); - Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTickDef, 1, 500, "mw.config.chunksPerTick"); - Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverrideDef, "mw.config.saveDirOverride"); - Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabledDef, "mw.config.portNumberInWorldNameEnabled"); - Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); - Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); - Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureMode", Config.backgroundModeStringArray); - Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); - Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); - - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "mw.config.textureSize"); - - Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "mw.config.overlayModeIndex"); - Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); - - Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); - - Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "mw.config.newMarkerDialog"); - Config.drawMarkersInWorld = configuration.getBoolean("drawMarkersInWorld", Reference.catOptions, Config.drawMarkersInWorldDef, "mw.config.drawMarkersInWorld"); - Config.drawMarkersNameInWorld = configuration.getBoolean("drawMarkersNameInWorld", Reference.catOptions, Config.drawMarkersNameInWorldDef, "mw.config.drawMarkersNameInWorld"); - Config.drawMarkersDistanceInWorld = configuration.getBoolean("drawMarkersDistanceInWorld", Reference.catOptions, Config.drawMarkersDistanceInWorldDef, "mw.config.drawMarkersDistanceInWorld"); - - Config.fullScreenMap.loadConfig(); - Config.largeMap.loadConfig(); - Config.smallMap.loadConfig(); - - if (configuration.hasChanged()) - { - configuration.save(); - } + configuration.save(); } + } - - @SubscribeEvent - public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) - { - if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) - { - loadConfig(); - } - } + @SubscribeEvent + public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) + { + if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) + { + loadConfig(); + } + } - public static void setMapModeDefaults() - { - Config.fullScreenMap.setDefaults(); - Config.largeMap.setDefaults(); - Config.smallMap.setDefaults(); - } - } \ No newline at end of file + public static void setMapModeDefaults() + { + Config.fullScreenMap.setDefaults(); + Config.largeMap.setDefaults(); + Config.smallMap.setDefaults(); + } +} \ No newline at end of file diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index ee5988a7..e04a0643 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -1,67 +1,71 @@ -package mapwriter.config; - -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; -import net.minecraftforge.fml.client.config.IConfigElement; - -public class MapModeConfig { - public final String configCategory; - public static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; - - public static final String[] miniMapPositionStringArray = { - "top right", - "top left", - "bottom right", - "bottom left" - }; - - public boolean enabledDef = true; - public boolean enabled = enabledDef; - public boolean rotateDef = false; - public boolean rotate = rotateDef; - public boolean circularDef = false; - public boolean circular = circularDef; - public String coordsModeDef = coordsModeStringArray[0]; - public String coordsMode = coordsModeDef; - public boolean borderModeDef = false; - public boolean borderMode = borderModeDef; - public int playerArrowSizeDef = 5; - public int playerArrowSize = playerArrowSizeDef; - public int markerSizeDef = 5; - public int markerSize = markerSizeDef; - public int trailMarkerSizeDef = 3; - public int trailMarkerSize = trailMarkerSizeDef; - public int alphaPercentDef = 100; - public int alphaPercent = alphaPercentDef; - public int heightPercentDef = -1; - public int heightPercent = heightPercentDef; - public String PositionDef = "FullScreen"; - public String Position = PositionDef; - - public MapModeConfig(String configCategory) { - this.configCategory = configCategory; - } - - public void loadConfig() { - // get options from config file - this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSizeDef, 1, 20, "mw.config.map.playerArrowSize"); - this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSizeDef, 1, 20, "mw.config.map.markerSize"); - this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "mw.config.map.alphaPercent"); - - this.trailMarkerSize = Math.max(1, this.markerSize - 1); - } - - public void setDefaults() - { - } - - public IConfigElement categoryElement(String name, String tooltip_key) - { - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); - } +package mapwriter.config; + +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.IConfigElement; + +public class MapModeConfig +{ + public final String configCategory; + public static final String[] coordsModeStringArray = + { + "disabled", + "small", + "large" + }; + + public static final String[] miniMapPositionStringArray = + { + "top right", + "top left", + "bottom right", + "bottom left" + }; + + public boolean enabledDef = true; + public boolean enabled = this.enabledDef; + public boolean rotateDef = false; + public boolean rotate = this.rotateDef; + public boolean circularDef = false; + public boolean circular = this.circularDef; + public String coordsModeDef = coordsModeStringArray[0]; + public String coordsMode = this.coordsModeDef; + public boolean borderModeDef = false; + public boolean borderMode = this.borderModeDef; + public int playerArrowSizeDef = 5; + public int playerArrowSize = this.playerArrowSizeDef; + public int markerSizeDef = 5; + public int markerSize = this.markerSizeDef; + public int trailMarkerSizeDef = 3; + public int trailMarkerSize = this.trailMarkerSizeDef; + public int alphaPercentDef = 100; + public int alphaPercent = this.alphaPercentDef; + public int heightPercentDef = -1; + public int heightPercent = this.heightPercentDef; + public String PositionDef = "FullScreen"; + public String Position = this.PositionDef; + + public MapModeConfig(String configCategory) + { + this.configCategory = configCategory; + } + + public void loadConfig() + { + // get options from config file + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSizeDef, 1, 20, "mw.config.map.playerArrowSize"); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSizeDef, 1, 20, "mw.config.map.markerSize"); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "mw.config.map.alphaPercent"); + + this.trailMarkerSize = Math.max(1, this.markerSize - 1); + } + + public void setDefaults() + { + } + + public IConfigElement categoryElement(String name, String tooltip_key) + { + return new DummyCategoryElement(name, tooltip_key, new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/config/WorldConfig.java b/src/main/java/mapwriter/config/WorldConfig.java index 599f0b59..a12eff3b 100644 --- a/src/main/java/mapwriter/config/WorldConfig.java +++ b/src/main/java/mapwriter/config/WorldConfig.java @@ -1,71 +1,79 @@ -package mapwriter.config; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.util.Reference; -import mapwriter.util.Utils; -import net.minecraftforge.common.config.Configuration; - -public class WorldConfig -{ - private static WorldConfig instance = null; - - public Configuration worldConfiguration = null; - - // list of available dimensions - public List dimensionList = new ArrayList(); - - private WorldConfig() - { - // load world specific config file - File worldConfigFile = new File(Mw.getInstance().worldDir, Reference.worldDirConfigName); - this.worldConfiguration = new Configuration(worldConfigFile); - - InitDimensionList(); - } - - public static WorldConfig getInstance() { - if (instance == null ) { - synchronized (WorldConfig.class) { - if (instance == null) { - instance = new WorldConfig(); - } - } - } - - return instance; - } - - public void saveWorldConfig() - { - this.worldConfiguration.save(); - } - - //Dimension List - public void InitDimensionList() - { - dimensionList.clear(); - this.worldConfiguration.get(Reference.catWorld, "dimensionList", Utils.integerListToIntArray(dimensionList)); - addDimension(0); - cleanDimensionList(); - } - - public void addDimension(int dimension) { - int i = dimensionList.indexOf(dimension); - if (i < 0) { - dimensionList.add(dimension); - } - } - - public void cleanDimensionList() { - List dimensionListCopy = new ArrayList(dimensionList); - dimensionList.clear(); - for (int dimension : dimensionListCopy) { - this.addDimension(dimension); - } - } - -} +package mapwriter.config; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.util.Reference; +import mapwriter.util.Utils; +import net.minecraftforge.common.config.Configuration; + +public class WorldConfig +{ + private static WorldConfig instance = null; + + public Configuration worldConfiguration = null; + + // list of available dimensions + public List dimensionList = new ArrayList(); + + private WorldConfig() + { + // load world specific config file + File worldConfigFile = new File(Mw.getInstance().worldDir, Reference.worldDirConfigName); + this.worldConfiguration = new Configuration(worldConfigFile); + + this.InitDimensionList(); + } + + public static WorldConfig getInstance() + { + if (instance == null) + { + synchronized (WorldConfig.class) + { + if (instance == null) + { + instance = new WorldConfig(); + } + } + } + + return instance; + } + + public void saveWorldConfig() + { + this.worldConfiguration.save(); + } + + // Dimension List + public void InitDimensionList() + { + this.dimensionList.clear(); + this.worldConfiguration.get(Reference.catWorld, "dimensionList", Utils.integerListToIntArray(this.dimensionList)); + this.addDimension(0); + this.cleanDimensionList(); + } + + public void addDimension(int dimension) + { + int i = this.dimensionList.indexOf(dimension); + if (i < 0) + { + this.dimensionList.add(dimension); + } + } + + public void cleanDimensionList() + { + List dimensionListCopy = new ArrayList(this.dimensionList); + this.dimensionList.clear(); + for (int dimension : dimensionListCopy) + { + this.addDimension(dimension); + } + } + +} diff --git a/src/main/java/mapwriter/config/largeMapModeConfig.java b/src/main/java/mapwriter/config/largeMapModeConfig.java index 57b31684..7a479c30 100644 --- a/src/main/java/mapwriter/config/largeMapModeConfig.java +++ b/src/main/java/mapwriter/config/largeMapModeConfig.java @@ -3,15 +3,16 @@ import mapwriter.gui.ModGuiConfig.ModBooleanEntry; import mapwriter.util.Reference; import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; +import net.minecraftforge.fml.client.config.IConfigElement; public class largeMapModeConfig extends MapModeConfig { - public largeMapModeConfig(String configCategory) { + public largeMapModeConfig(String configCategory) + { super(configCategory); } - + @Override public void loadConfig() { @@ -22,28 +23,27 @@ public void loadConfig() this.coordsMode = ConfigurationHandler.configuration.getString("coordsMode", this.configCategory, this.coordsModeDef, "mw.config.map.coordsMode", coordsModeStringArray); this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderModeDef, "mw.config.map.borderMode"); } - + @Override public void setDefaults() { this.rotateDef = true; this.circularDef = true; - this.coordsModeDef = coordsModeStringArray[1]; + this.coordsModeDef = coordsModeStringArray[1]; this.borderModeDef = true; this.heightPercentDef = -1; this.PositionDef = "Large"; this.Position = this.PositionDef; - + ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", this.enabled).setRequiresWorldRestart(true); } - + @Override - public IConfigElement categoryElement(String name, String tooltip_key) - { - ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); - - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); - } + public IConfigElement categoryElement(String name, String tooltip_key) + { + ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); + + return new DummyCategoryElement(name, tooltip_key, new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); + } } diff --git a/src/main/java/mapwriter/config/smallMapModeConfig.java b/src/main/java/mapwriter/config/smallMapModeConfig.java index d9f37bb8..a13c9c32 100644 --- a/src/main/java/mapwriter/config/smallMapModeConfig.java +++ b/src/main/java/mapwriter/config/smallMapModeConfig.java @@ -1,34 +1,34 @@ -package mapwriter.config; - -import mapwriter.util.Reference; - -public class smallMapModeConfig extends largeMapModeConfig -{ - public smallMapModeConfig(String configCategory) - { - super(configCategory); - } - - @Override - public void loadConfig() - { - super.loadConfig(); - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent",this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); - this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); - } - - @Override - public void setDefaults() - { - this.rotateDef = true; - this.circularDef = true; - this.coordsModeDef = coordsModeStringArray[1]; - this.borderModeDef = true; - this.playerArrowSizeDef = 4; - this.markerSizeDef = 3; - this.heightPercentDef = 30; - this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; - - ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); - } -} +package mapwriter.config; + +import mapwriter.util.Reference; + +public class smallMapModeConfig extends largeMapModeConfig +{ + public smallMapModeConfig(String configCategory) + { + super(configCategory); + } + + @Override + public void loadConfig() + { + super.loadConfig(); + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent", this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); + this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); + } + + @Override + public void setDefaults() + { + this.rotateDef = true; + this.circularDef = true; + this.coordsModeDef = coordsModeStringArray[1]; + this.borderModeDef = true; + this.playerArrowSizeDef = 4; + this.markerSizeDef = 3; + this.heightPercentDef = 30; + this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; + + ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); + } +} diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java index 28acdd3f..aaf61d58 100644 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -1,58 +1,65 @@ -package mapwriter.forge; - -import java.io.File; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.config.ConfigurationHandler; -import mapwriter.overlay.OverlayGrid; -import mapwriter.overlay.OverlaySlime; -import mapwriter.region.MwChunk; -import mapwriter.util.Reference; -import mapwriter.util.VersionCheck; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.event.FMLInterModComms; - - -public class ClientProxy extends CommonProxy { - - public void preInit(File configFile) - { - ConfigurationHandler.init(configFile); - FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); - } - - public void load() { - EventHandler eventHandler = new EventHandler(Mw.getInstance()); - MinecraftForge.EVENT_BUS.register(eventHandler); - FMLCommonHandler.instance().bus().register(eventHandler); - - MwKeyHandler keyEventHandler = new MwKeyHandler(); - FMLCommonHandler.instance().bus().register(keyEventHandler); - MinecraftForge.EVENT_BUS.register(keyEventHandler); - } - - public void postInit() { - if (Loader.isModLoaded("VersionChecker")) - { - FMLInterModComms.sendRuntimeMessage(Reference.MOD_ID, "VersionChecker", "addVersionCheck", Reference.VersionURL); - } - else - { - VersionCheck versionCheck = new VersionCheck(); - Thread versionCheckThread = new Thread(versionCheck, "Version Check"); - versionCheckThread.start(); - } - if (Loader.isModLoaded("CarpentersBlocks")) { - MwChunk.carpenterdata(); - } - if (Loader.isModLoaded("ForgeMultipart")) { - MwChunk.FMPdata(); - - } - MwAPI.registerDataProvider("Slime", new OverlaySlime()); - MwAPI.registerDataProvider("Grid", new OverlayGrid()); - } -} +package mapwriter.forge; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.config.ConfigurationHandler; +import mapwriter.overlay.OverlayGrid; +import mapwriter.overlay.OverlaySlime; +import mapwriter.region.MwChunk; +import mapwriter.util.Reference; +import mapwriter.util.VersionCheck; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.event.FMLInterModComms; + +public class ClientProxy extends CommonProxy +{ + + @Override + public void preInit(File configFile) + { + ConfigurationHandler.init(configFile); + FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); + } + + @Override + public void load() + { + EventHandler eventHandler = new EventHandler(Mw.getInstance()); + MinecraftForge.EVENT_BUS.register(eventHandler); + FMLCommonHandler.instance().bus().register(eventHandler); + + MwKeyHandler keyEventHandler = new MwKeyHandler(); + FMLCommonHandler.instance().bus().register(keyEventHandler); + MinecraftForge.EVENT_BUS.register(keyEventHandler); + } + + @Override + public void postInit() + { + if (Loader.isModLoaded("VersionChecker")) + { + FMLInterModComms.sendRuntimeMessage(Reference.MOD_ID, "VersionChecker", "addVersionCheck", Reference.VersionURL); + } + else + { + VersionCheck versionCheck = new VersionCheck(); + Thread versionCheckThread = new Thread(versionCheck, "Version Check"); + versionCheckThread.start(); + } + if (Loader.isModLoaded("CarpentersBlocks")) + { + MwChunk.carpenterdata(); + } + if (Loader.isModLoaded("ForgeMultipart")) + { + MwChunk.FMPdata(); + + } + MwAPI.registerDataProvider("Slime", new OverlaySlime()); + MwAPI.registerDataProvider("Grid", new OverlayGrid()); + } +} diff --git a/src/main/java/mapwriter/forge/CommonProxy.java b/src/main/java/mapwriter/forge/CommonProxy.java index 6ef4209b..0ada12cf 100644 --- a/src/main/java/mapwriter/forge/CommonProxy.java +++ b/src/main/java/mapwriter/forge/CommonProxy.java @@ -2,8 +2,17 @@ import java.io.File; -public class CommonProxy { - public void preInit(File configFile) {} - public void load() {} - public void postInit() {} +public class CommonProxy +{ + public void preInit(File configFile) + { + } + + public void load() + { + } + + public void postInit() + { + } } diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index 561ac5ef..b7fac390 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -14,84 +14,106 @@ import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -public class EventHandler { +public class EventHandler +{ Mw mw; - public EventHandler(Mw mw) { + public EventHandler(Mw mw) + { this.mw = mw; } @SubscribeEvent - public void eventChunkLoad(ChunkEvent.Load event) { - if (event.world.isRemote) { + public void eventChunkLoad(ChunkEvent.Load event) + { + if (event.world.isRemote) + { this.mw.onChunkLoad(event.getChunk()); } } @SubscribeEvent - public void eventChunkUnload(ChunkEvent.Unload event) { - if (event.world.isRemote) { + public void eventChunkUnload(ChunkEvent.Unload event) + { + if (event.world.isRemote) + { this.mw.onChunkUnload(event.getChunk()); } } @SubscribeEvent - public void onClientChat(ClientChatReceivedEvent event) { + public void onClientChat(ClientChatReceivedEvent event) + { if (OverlaySlime.seedFound || !OverlaySlime.seedAsked) + { return; - try { // I don't want to crash the game when we derp up in here - if (event.message instanceof ChatComponentTranslation) { + } + try + { // I don't want to crash the game when we derp up in here + if (event.message instanceof ChatComponentTranslation) + { ChatComponentTranslation component = (ChatComponentTranslation) event.message; - if (component.getKey().equals("commands.seed.success")) { + if (component.getKey().equals("commands.seed.success")) + { OverlaySlime.setSeed((Long) component.getFormatArgs()[0]); event.setCanceled(true); // Don't let the player see this - // seed message, They didn't do - // /seed, we did + // seed message, They didn't do + // /seed, we did } - } else if (event.message instanceof ChatComponentText) { + } + else if (event.message instanceof ChatComponentText) + { ChatComponentText component = (ChatComponentText) event.message; String msg = component.getUnformattedText(); - if (msg.startsWith("Seed: ")) { // Because bukkit... + if (msg.startsWith("Seed: ")) + { // Because bukkit... OverlaySlime.setSeed(Long.parseLong(msg.substring(6))); event.setCanceled(true); // Don't let the player see this - // seed message, They didn't do - // /seed, we did + // seed message, They didn't do + // /seed, we did } } - } catch (Exception e) { + } + catch (Exception e) + { // e.printStackTrace(); } } @SubscribeEvent(priority = EventPriority.LOWEST) - public void eventPlayerDeath(LivingDeathEvent event) { - if (!event.isCanceled()) { - if (event.entityLiving.getEntityId() == net.minecraft.client.Minecraft - .getMinecraft().thePlayer.getEntityId()) { - this.mw.onPlayerDeath((EntityPlayerMP)event.entityLiving); + public void eventPlayerDeath(LivingDeathEvent event) + { + if (!event.isCanceled()) + { + if (event.entityLiving.getEntityId() == net.minecraft.client.Minecraft.getMinecraft().thePlayer.getEntityId()) + { + this.mw.onPlayerDeath((EntityPlayerMP) event.entityLiving); } } } - - @SubscribeEvent - public void renderMap(RenderGameOverlayEvent.Post event){ - if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - Mw.getInstance().onTick(); - } - } - - @SubscribeEvent - public void onTextureStitchEventPost(TextureStitchEvent.Post event){ - mw.reloadBlockColours(); - } - @SubscribeEvent - public void renderWorldLastEvent(RenderWorldLastEvent event) - { - if (Mw.getInstance().ready) - { - Mw.getInstance().markerManager.drawMarkersWorld(event.partialTicks); - } - } + @SubscribeEvent + public void renderMap(RenderGameOverlayEvent.Post event) + { + if (event.type == RenderGameOverlayEvent.ElementType.ALL) + { + Mw.getInstance().onTick(); + } + } + + @SubscribeEvent + public void onTextureStitchEventPost(TextureStitchEvent.Post event) + { + this.mw.reloadBlockColours(); + } + + @SubscribeEvent + public void renderWorldLastEvent(RenderWorldLastEvent event) + { + if (Mw.getInstance().ready) + { + Mw.getInstance().markerManager.drawMarkersWorld(event.partialTicks); + } + } } diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index 0c2eeb76..f194416c 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -1,57 +1,66 @@ -package mapwriter.forge; - -import mapwriter.Mw; -import mapwriter.util.Reference; -import net.minecraft.client.Minecraft; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.Mod.Instance; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -@Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS, clientSideOnly=true ) -public class MwForge { - - @Instance(Reference.MOD_ID) - public static MwForge instance; - - @SidedProxy(clientSide=Reference.CLIENT_PROXY_CLASS) - public static CommonProxy proxy; - - public static Logger logger = LogManager.getLogger(Reference.MOD_ID); - - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - FMLCommonHandler.instance().bus().register(this); - proxy.preInit(event.getSuggestedConfigurationFile()); - } - - @EventHandler - public void load(FMLInitializationEvent event) { - proxy.load(); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - proxy.postInit(); - } - - @SubscribeEvent - public void onTick(TickEvent.ClientTickEvent event){ - if (event.phase == TickEvent.Phase.START){ - // run the cleanup code when Mw is loaded and the player becomes null. - // a bit hacky, but simpler than checking if the connection has closed. - if ((Mw.getInstance().ready) && (Minecraft.getMinecraft().thePlayer == null)) { - Mw.getInstance().close(); - } - } - } -} +package mapwriter.forge; + +import mapwriter.Mw; +import mapwriter.util.Reference; +import net.minecraft.client.Minecraft; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.EventHandler; +import net.minecraftforge.fml.common.Mod.Instance; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS, clientSideOnly = true) +public class MwForge +{ + + @Instance(Reference.MOD_ID) + public static MwForge instance; + + @SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS) + public static CommonProxy proxy; + + public static Logger logger = LogManager.getLogger(Reference.MOD_ID); + + @EventHandler + public void preInit(FMLPreInitializationEvent event) + { + FMLCommonHandler.instance().bus().register(this); + proxy.preInit(event.getSuggestedConfigurationFile()); + } + + @EventHandler + public void load(FMLInitializationEvent event) + { + proxy.load(); + } + + @EventHandler + public void postInit(FMLPostInitializationEvent event) + { + proxy.postInit(); + } + + @SubscribeEvent + public void onTick(TickEvent.ClientTickEvent event) + { + if (event.phase == TickEvent.Phase.START) + { + // run the cleanup code when Mw is loaded and the player becomes + // null. + // a bit hacky, but simpler than checking if the connection has + // closed. + if ((Mw.getInstance().ready) && (Minecraft.getMinecraft().thePlayer == null)) + { + Mw.getInstance().close(); + } + } + } +} diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index ad61cfd9..8b3deaf9 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -1,86 +1,86 @@ -package mapwriter.forge; - -import java.util.ArrayList; - -import mapwriter.Mw; -import mapwriter.util.Reference; -import modwarriors.notenoughkeys.api.Api; -import modwarriors.notenoughkeys.api.KeyBindingPressedEvent; -import net.minecraft.client.settings.KeyBinding; -import net.minecraftforge.fml.client.registry.ClientRegistry; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.Optional; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.InputEvent; - -import org.lwjgl.input.Keyboard; - -public class MwKeyHandler { - public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); - public static KeyBinding keyNewMarker = new KeyBinding("key.mw_new_marker", Keyboard.KEY_INSERT, "Mapwriter"); - public static KeyBinding keyMapMode = new KeyBinding("key.mw_next_map_mode", Keyboard.KEY_N, "Mapwriter"); - public static KeyBinding keyNextGroup = new KeyBinding("key.mw_next_marker_group", Keyboard.KEY_COMMA, "Mapwriter"); - public static KeyBinding keyTeleport = new KeyBinding("key.mw_teleport", Keyboard.KEY_PERIOD, "Mapwriter"); - public static KeyBinding keyZoomIn = new KeyBinding("key.mw_zoom_in", Keyboard.KEY_PRIOR, "Mapwriter"); - public static KeyBinding keyZoomOut = new KeyBinding("key.mw_zoom_out", Keyboard.KEY_NEXT, "Mapwriter"); - public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); - //public static KeyBinding keyQuickLargeMap = new KeyBinding("key.mw_quick_large_map", Keyboard.KEY_NONE); - - public final KeyBinding[] keys = - { - keyMapGui, - keyNewMarker, - keyMapMode, - keyNextGroup, - keyTeleport, - keyZoomIn, - keyZoomOut, - keyUndergroundMode - }; - - public MwKeyHandler() - { - ArrayList listKeyDescs = new ArrayList(); - // Register bindings - for (KeyBinding key : this.keys) - { - if (key != null) - { - ClientRegistry.registerKeyBinding(key); - } - listKeyDescs.add(key.getKeyDescription()); - } - - if (Loader.isModLoaded("notenoughkeys")) - { - Api.registerMod(Reference.MOD_ID, listKeyDescs.toArray(new String[0])); - } - } - - @SubscribeEvent - public void keyEvent(InputEvent.KeyInputEvent event) - { - if (!Loader.isModLoaded("notenoughkeys")) - { - this.checkKeys(); - } - } - - @Optional.Method(modid = "notenoughkeys") - @SubscribeEvent - public void keyEventSpecial(KeyBindingPressedEvent event) - { - Mw.getInstance().onKeyDown(event.keyBinding); - } - - private void checkKeys() - { - for (KeyBinding key : keys) - { - if (key != null && key.isPressed()) - { - Mw.getInstance().onKeyDown(key); - } - } - } -} +package mapwriter.forge; + +import java.util.ArrayList; + +import mapwriter.Mw; +import mapwriter.util.Reference; +import modwarriors.notenoughkeys.api.Api; +import modwarriors.notenoughkeys.api.KeyBindingPressedEvent; +import net.minecraft.client.settings.KeyBinding; +import net.minecraftforge.fml.client.registry.ClientRegistry; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.Optional; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.InputEvent; + +import org.lwjgl.input.Keyboard; + +public class MwKeyHandler +{ + public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); + public static KeyBinding keyNewMarker = new KeyBinding("key.mw_new_marker", Keyboard.KEY_INSERT, "Mapwriter"); + public static KeyBinding keyMapMode = new KeyBinding("key.mw_next_map_mode", Keyboard.KEY_N, "Mapwriter"); + public static KeyBinding keyNextGroup = new KeyBinding("key.mw_next_marker_group", Keyboard.KEY_COMMA, "Mapwriter"); + public static KeyBinding keyTeleport = new KeyBinding("key.mw_teleport", Keyboard.KEY_PERIOD, "Mapwriter"); + public static KeyBinding keyZoomIn = new KeyBinding("key.mw_zoom_in", Keyboard.KEY_PRIOR, "Mapwriter"); + public static KeyBinding keyZoomOut = new KeyBinding("key.mw_zoom_out", Keyboard.KEY_NEXT, "Mapwriter"); + public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); + + public final KeyBinding[] keys = + { + keyMapGui, + keyNewMarker, + keyMapMode, + keyNextGroup, + keyTeleport, + keyZoomIn, + keyZoomOut, + keyUndergroundMode + }; + + public MwKeyHandler() + { + ArrayList listKeyDescs = new ArrayList(); + // Register bindings + for (KeyBinding key : this.keys) + { + if (key != null) + { + ClientRegistry.registerKeyBinding(key); + } + listKeyDescs.add(key.getKeyDescription()); + } + + if (Loader.isModLoaded("notenoughkeys")) + { + Api.registerMod(Reference.MOD_ID, listKeyDescs.toArray(new String[0])); + } + } + + @SubscribeEvent + public void keyEvent(InputEvent.KeyInputEvent event) + { + if (!Loader.isModLoaded("notenoughkeys")) + { + this.checkKeys(); + } + } + + @Optional.Method(modid = "notenoughkeys") + @SubscribeEvent + public void keyEventSpecial(KeyBindingPressedEvent event) + { + Mw.getInstance().onKeyDown(event.keyBinding); + } + + private void checkKeys() + { + for (KeyBinding key : this.keys) + { + if ((key != null) && key.isPressed()) + { + Mw.getInstance().onKeyDown(key); + } + } + } +} diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index c4a48e21..37378bee 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -20,133 +20,140 @@ public class ModGuiConfig extends GuiConfig { - public ModGuiConfig(GuiScreen guiScreen) - { - super(guiScreen, - getConfigElements(), - //new ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), - Reference.MOD_ID, - "Options", - false, - false, - GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); - } - - /** Compiles a list of config elements */ - private static List getConfigElements() - { - List list = new ArrayList(); - - //Add categories to config GUI - list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); - list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); - list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); - list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); - return list; - } - - /** Creates a button linking to another screen where all options of the category are available */ - private static IConfigElement categoryElement(String category, String name, String tooltip_key) - { - return new DummyCategoryElement(name, tooltip_key, - new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); - } - - public static class ModBooleanEntry extends ButtonEntry - { - protected final boolean beforeValue; - protected boolean currentValue; - - public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) - { - super(owningScreen, owningEntryList, configElement); - this.beforeValue = Boolean.valueOf(configElement.get().toString()); - this.currentValue = beforeValue; - this.btnValue.enabled = enabled(); - updateValueButtonText(); - } - - @Override - public void updateValueButtonText() - { - this.btnValue.displayString = I18n.format(String.valueOf(currentValue)); - btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); - } - - @Override - public void valueButtonPressed(int slotIndex) - { - if (enabled()) - currentValue = !currentValue; - } - - @Override - public boolean isDefault() - { - return currentValue == Boolean.valueOf(configElement.getDefault().toString()); - } - - @Override - public void setToDefault() - { - if (enabled()) - { - currentValue = Boolean.valueOf(configElement.getDefault().toString()); - updateValueButtonText(); - } - } - - @Override - public boolean isChanged() - { - return currentValue != beforeValue; - } - - @Override - public void undoChanges() - { - if (enabled()) - { - currentValue = beforeValue; - updateValueButtonText(); - } - } - - @Override - public boolean saveConfigElement() - { - if (enabled() && isChanged()) - { - configElement.set(currentValue); - return configElement.requiresMcRestart(); - } - return false; - } - - @Override - public Boolean getCurrentValue() - { - return currentValue; - } - - @Override - public Boolean[] getCurrentValues() - { - return new Boolean[] { getCurrentValue() }; - } - - @Override - public boolean enabled() - { - for (IConfigEntry entry : this.owningEntryList.listEntries) - { - if (entry.getName().equals("circular") && entry instanceof BooleanEntry) - { - return Boolean.valueOf(entry.getCurrentValue().toString()); - } - } - - return true; - } - } + public ModGuiConfig(GuiScreen guiScreen) + { + super(guiScreen, getConfigElements(), + // new + // ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + Reference.MOD_ID, + "Options", + false, + false, + GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString())); + } + + /** Compiles a list of config elements */ + private static List getConfigElements() + { + List list = new ArrayList(); + + // Add categories to config GUI + list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); + list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); + list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); + list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); + return list; + } + + /** + * Creates a button linking to another screen where all options of the + * category are available + */ + private static IConfigElement categoryElement(String category, String name, String tooltip_key) + { + return new DummyCategoryElement(name, tooltip_key, new ConfigElement(ConfigurationHandler.configuration.getCategory(category)).getChildElements()); + } + + public static class ModBooleanEntry extends ButtonEntry + { + protected final boolean beforeValue; + protected boolean currentValue; + + public ModBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement) + { + super(owningScreen, owningEntryList, configElement); + this.beforeValue = Boolean.valueOf(configElement.get().toString()); + this.currentValue = this.beforeValue; + this.btnValue.enabled = this.enabled(); + this.updateValueButtonText(); + } + + @Override + public void updateValueButtonText() + { + this.btnValue.displayString = I18n.format(String.valueOf(this.currentValue)); + this.btnValue.packedFGColour = this.currentValue ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true); + } + + @Override + public void valueButtonPressed(int slotIndex) + { + if (this.enabled()) + { + this.currentValue = !this.currentValue; + } + } + + @Override + public boolean isDefault() + { + return this.currentValue == Boolean.valueOf(this.configElement.getDefault().toString()); + } + + @Override + public void setToDefault() + { + if (this.enabled()) + { + this.currentValue = Boolean.valueOf(this.configElement.getDefault().toString()); + this.updateValueButtonText(); + } + } + + @Override + public boolean isChanged() + { + return this.currentValue != this.beforeValue; + } + + @Override + public void undoChanges() + { + if (this.enabled()) + { + this.currentValue = this.beforeValue; + this.updateValueButtonText(); + } + } + + @Override + public boolean saveConfigElement() + { + if (this.enabled() && this.isChanged()) + { + this.configElement.set(this.currentValue); + return this.configElement.requiresMcRestart(); + } + return false; + } + + @Override + public Boolean getCurrentValue() + { + return this.currentValue; + } + + @Override + public Boolean[] getCurrentValues() + { + return new Boolean[] + { + this.getCurrentValue() + }; + } + + @Override + public boolean enabled() + { + for (IConfigEntry entry : this.owningEntryList.listEntries) + { + if (entry.getName().equals("circular") && (entry instanceof BooleanEntry)) + { + return Boolean.valueOf(entry.getCurrentValue().toString()); + } + } + + return true; + } + } } diff --git a/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java index 35f3e8af..898b1f47 100644 --- a/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java +++ b/src/main/java/mapwriter/gui/ModGuiFactoryHandler.java @@ -10,23 +10,25 @@ public class ModGuiFactoryHandler implements IModGuiFactory { @Override - public void initialize(Minecraft minecraftInstance) { - + public void initialize(Minecraft minecraftInstance) + { } @Override - public Class mainConfigGuiClass() { + public Class mainConfigGuiClass() + { return ModGuiConfig.class; } @Override - public Set runtimeGuiCategories() { + public Set runtimeGuiCategories() + { return null; } @Override - public RuntimeOptionGuiHandler getHandlerFor( - RuntimeOptionCategoryElement element) { + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) + { return null; } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 8f8d00e5..6073a0db 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -34,16 +34,18 @@ import org.lwjgl.input.Mouse; @SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { +public class MwGui extends GuiScreen +{ private Mw mw; public MapMode mapMode; private MapView mapView; private MapRenderer map; - private String[] HelpText1 = new String[]{ + private String[] HelpText1 = new String[] + { "Keys:", "", - " Space", + " Space", " Delete", " C", " Home", @@ -56,24 +58,25 @@ public class MwGui extends GuiScreen { " L", "", "mw.gui.mwgui.helptext.1", - "mw.gui.mwgui.helptext.2", - "mw.gui.mwgui.helptext.3", - "mw.gui.mwgui.helptext.4", - "mw.gui.mwgui.helptext.5", + "mw.gui.mwgui.helptext.2", + "mw.gui.mwgui.helptext.3", + "mw.gui.mwgui.helptext.4", + "mw.gui.mwgui.helptext.5", "mw.gui.mwgui.helptext.6", "", "mw.gui.mwgui.helptext.7", "mw.gui.mwgui.helptext.8", "mw.gui.mwgui.helptext.9" }; - private String[] HelpText2 = new String[]{ + private String[] HelpText2 = new String[] + { "", "", - "mw.gui.mwgui.helptext.nextmarkergroup", + "mw.gui.mwgui.helptext.nextmarkergroup", "mw.gui.mwgui.helptext.deletemarker", - "mw.gui.mwgui.helptext.cyclecolour", + "mw.gui.mwgui.helptext.cyclecolour", "mw.gui.mwgui.helptext.centermap", - "mw.gui.mwgui.helptext.centermapplayer", + "mw.gui.mwgui.helptext.centermapplayer", "mw.gui.mwgui.helptext.selectnextmarker", "mw.gui.mwgui.helptext.teleport", "mw.gui.mwgui.helptext.savepng", @@ -81,7 +84,7 @@ public class MwGui extends GuiScreen { "mw.gui.mwgui.helptext.undergroundmap", "mw.gui.mwgui.helptext.markerlist" }; - + private final static double PAN_FACTOR = 0.3D; private static final int menuY = 5; @@ -106,7 +109,7 @@ public class MwGui extends GuiScreen { private MwGuiLabel overlayLabel; private MwGuiLabel updateLabel; private MwGuiMarkerListOverlay MarkerOverlay; - + private MwGuiLabel helpTooltipLabel; private MwGuiLabel updateTooltipLabel; private MwGuiLabel statusLabel; @@ -116,25 +119,26 @@ public class MwGui extends GuiScreen { private URI clickedLinkURI; - public MwGui(Mw mw) { + public MwGui(Mw mw) + { this.mw = mw; this.mapMode = new FullScreenMapMode(); this.mapView = new MapView(this.mw, true); this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); this.mapView.setZoomLevel(Config.fullScreenZoomLevel); this.initLabels(); - + this.MarkerOverlay = new MwGuiMarkerListOverlay(this, this.mw.markerManager); - + instance = this; } - public MwGui(Mw mw, int dim, int x, int z) { + public MwGui(Mw mw, int dim, int x, int z) + { this(mw); this.mapView.setDimension(dim); this.mapView.setViewCentreScaled(x, z, dim); @@ -143,7 +147,8 @@ public MwGui(Mw mw, int dim, int x, int z) { // called when gui is displayed and every time the screen // is resized - public void initGui() + @Override + public void initGui() { this.helpLabel.setParentWidthAndHeight(this.width, this.height); this.optionsLabel.setParentWidthAndHeight(this.width, this.height); @@ -151,149 +156,72 @@ public void initGui() this.groupLabel.setParentWidthAndHeight(this.width, this.height); this.overlayLabel.setParentWidthAndHeight(this.width, this.height); this.updateLabel.setParentWidthAndHeight(this.width, this.height); - + this.helpTooltipLabel.setParentWidthAndHeight(this.width, this.height); this.updateTooltipLabel.setParentWidthAndHeight(this.width, this.height); this.statusLabel.setParentWidthAndHeight(this.width, this.height); this.markerLabel.setParentWidthAndHeight(this.width, this.height); - - MarkerOverlay.setDimensions(MarkerOverlay.listWidth, this.height - 20, MarkerOverlay.ListY, 10 + this.height - 20, this.width - 110); + + this.MarkerOverlay.setDimensions(MwGuiMarkerListOverlay.listWidth, this.height - 20, MwGuiMarkerListOverlay.ListY, (10 + this.height) - 20, this.width - 110); } public void initLabels() { - this.helpLabel = new MwGuiLabel( - new String[]{"[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]"}, - null, - menuX, - menuY, - true, - false, - this.width, - this.height - ); - this.optionsLabel = new MwGuiLabel( - new String[]{"[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]"}, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - this.dimensionLabel = new MwGuiLabel( - null, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - this.groupLabel = new MwGuiLabel( - null, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - this.overlayLabel = new MwGuiLabel( - null, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - String updateString = String.format( - "[" + I18n.format("mw.gui.mwgui.newversion", - new Object[0]) + ": %s]", - VersionCheck.getLatestVersion() - ); - this.updateLabel = new MwGuiLabel( - new String[]{updateString}, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - this.helpTooltipLabel = new MwGuiLabel( - HelpText1, - HelpText2, - 0, - 0, - true, - false, - this.width, - this.height - ); - - this.updateTooltipLabel = new MwGuiLabel( - new String[]{VersionCheck.getUpdateURL()}, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - - this.statusLabel = new MwGuiLabel( - null, - null, - 0, - 0, - true, - false, - this.width, - this.height - ); - this.markerLabel = new MwGuiLabel( - null, - null, - 0, - 0, - true, - true, - this.width, - this.height - ); - + this.helpLabel = new MwGuiLabel(new String[] + { + "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]" + }, null, menuX, menuY, true, false, this.width, this.height); + this.optionsLabel = new MwGuiLabel(new String[] + { + "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]" + }, null, 0, 0, true, false, this.width, this.height); + this.dimensionLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); + this.groupLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); + this.overlayLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); + String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", VersionCheck.getLatestVersion()); + this.updateLabel = new MwGuiLabel(new String[] + { + updateString + }, null, 0, 0, true, false, this.width, this.height); + this.helpTooltipLabel = new MwGuiLabel(this.HelpText1, this.HelpText2, 0, 0, true, false, this.width, this.height); + + this.updateTooltipLabel = new MwGuiLabel(new String[] + { + VersionCheck.getUpdateURL() + }, null, 0, 0, true, false, this.width, this.height); + + this.statusLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); + this.markerLabel = new MwGuiLabel(null, null, 0, 0, true, true, this.width, this.height); + this.optionsLabel.drawToRightOf(this.helpLabel); this.dimensionLabel.drawToRightOf(this.optionsLabel); this.groupLabel.drawToRightOf(this.dimensionLabel); this.overlayLabel.drawToRightOf(this.groupLabel); this.updateLabel.drawToRightOf(this.overlayLabel); - + this.helpTooltipLabel.drawToBelowOf(this.helpLabel); this.updateTooltipLabel.drawToBelowOf(this.helpLabel); } - + // called when a button is pressed - protected void actionPerformed(GuiButton button) + @Override + protected void actionPerformed(GuiButton button) { } - + // get a marker near the specified block pos if it exists. // the maxDistance is based on the view width so that you need to click // closer // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { + public Marker getMarkerNearScreenPos(int x, int y) + { Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { + for (Marker marker : this.mw.markerManager.visibleMarkerList) + { + if (marker.screenPos != null) + { + if (marker.screenPos.distanceSq(x, y) < 6.0) + { nearMarker = marker; } } @@ -301,64 +229,63 @@ public Marker getMarkerNearScreenPos(int x, int y) { return nearMarker; } - public int getHeightAtBlockPos(int bX, int bZ) { + public int getHeightAtBlockPos(int bX, int bZ) + { int bY = 0; int worldDimension = this.mw.mc.theWorld.provider.getDimensionId(); - if ((worldDimension == this.mapView.getDimension()) - && (worldDimension != -1)) { + if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) + { bY = this.mw.mc.theWorld.getHeight(new BlockPos(bX, 0, bZ)).getY(); } return bY; } - public boolean isPlayerNearScreenPos(int x, int y) { + public boolean isPlayerNearScreenPos(int x, int y) + { Point.Double p = this.map.playerArrowScreenPos; return p.distanceSq(x, y) < 9.0; } - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { + public void deleteSelectedMarker() + { + if (this.mw.markerManager.selectedMarker != null) + { // MwUtil.log("deleting marker %s", // this.mw.markerManager.selectedMarker.name); - this.mw.markerManager - .delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); this.mw.markerManager.update(); this.mw.markerManager.selectedMarker = null; } } - public void mergeMapViewToImage() { + public void mergeMapViewToImage() + { this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir - .getName())); - - Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() - + "'"); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, (int) this.mapView.getX(), (int) this.mapView.getZ(), (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir.getName())); + + Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() + "'"); } - public void regenerateView() { + public void regenerateView() + { Utils.printBoth(String.format( - I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + - " %dx%d " + - I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + - " (%d, %d)", - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ())); + I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + " %dx%d " + I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + " (%d, %d)", + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ())); // this.mw.reloadBlockColours(); - this.mw.executor.addTask(new RebuildRegionsTask(this.mw, - (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), - this.mapView.getDimension())); + this.mw.executor.addTask(new RebuildRegionsTask(this.mw, (int) this.mapView.getMinX(), (int) this.mapView.getMinZ(), (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), this.mapView.getDimension())); } // c is the ascii equivalent of the key typed. // key is the lwjgl key code. - protected void keyTyped(char c, int key) { + @Override + protected void keyTyped(char c, int key) + { // MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch (key) { + switch (key) + { case Keyboard.KEY_ESCAPE: this.exitGui(); break; @@ -375,7 +302,8 @@ protected void keyTyped(char c, int key) { case Keyboard.KEY_C: // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { + if (this.mw.markerManager.selectedMarker != null) + { this.mw.markerManager.selectedMarker.colourNext(); } break; @@ -387,8 +315,7 @@ protected void keyTyped(char c, int key) { case Keyboard.KEY_HOME: // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, - this.mw.playerDimension); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); break; case Keyboard.KEY_END: @@ -402,13 +329,14 @@ protected void keyTyped(char c, int key) { break; case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { + if (this.mw.markerManager.selectedMarker != null) + { this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); this.exitGui(); - } else { - this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, - this.mapView, this.mouseBlockX, - Config.defaultTeleportHeight, this.mouseBlockZ)); + } + else + { + this.mc.displayGuiScreen(new MwGuiTeleportDialog(this, this.mw, this.mapView, this.mouseBlockX, Config.defaultTeleportHeight, this.mouseBlockZ)); } break; @@ -429,22 +357,31 @@ protected void keyTyped(char c, int key) { this.regenerateView(); this.exitGui(); break; - + case Keyboard.KEY_L: this.MarkerOverlay.setEnabled(!this.MarkerOverlay.getEnabled()); break; - + default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + if (key == MwKeyHandler.keyMapGui.getKeyCode()) + { this.exitGui(); - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + } + else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) + { this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + } + else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) + { this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + } + else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) + { this.mw.markerManager.nextGroup(); this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + } + else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) + { this.mw.toggleUndergroundMode(); this.mapView.setUndergroundMode(Config.undergroundMode); } @@ -455,23 +392,23 @@ protected void keyTyped(char c, int key) { // override GuiScreen's handleMouseInput to process // the scroll wheel. @Override - public void handleMouseInput() throws IOException { - if (this.MarkerOverlay.isMouseInField() && this.mouseLeftHeld == 0) + public void handleMouseInput() throws IOException + { + if (this.MarkerOverlay.isMouseInField() && (this.mouseLeftHeld == 0)) { this.MarkerOverlay.handleMouseInput(); } - else if (MwAPI.getCurrentDataProvider() != null && - MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) + else if ((MwAPI.getCurrentDataProvider() != null) && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) { - return; + return; } else { - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height - / this.mc.displayHeight - 1; + int x = (Mouse.getEventX() * this.width) / this.mc.displayWidth; + int y = this.height - ((Mouse.getEventY() * this.height) / this.mc.displayHeight) - 1; int direction = Mouse.getEventDWheel(); - if (direction != 0) { + if (direction != 0) + { this.mouseDWheelScrolled(x, y, direction); } } @@ -479,64 +416,78 @@ else if (MwAPI.getCurrentDataProvider() != null && } // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) { + @Override + protected void mouseClicked(int x, int y, int button) + { Marker marker = this.getMarkerNearScreenPos(x, y); Marker prevMarker = this.mw.markerManager.selectedMarker; - if (this.MarkerOverlay.isMouseInField() && this.mouseLeftHeld == 0) + if (this.MarkerOverlay.isMouseInField() && (this.mouseLeftHeld == 0)) { this.MarkerOverlay.handleMouseInput(); } else { - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, - this.mw, this.mapView, this.mapView.getDimension())); - } else if (this.optionsLabel.posWithin(x, y)) { - try { - GuiScreen newScreen = ModGuiConfig.class.getConstructor( - GuiScreen.class).newInstance(this); + if (button == 0) + { + if (this.dimensionLabel.posWithin(x, y)) + { + this.mc.displayGuiScreen(new MwGuiDimensionDialog(this, this.mw, this.mapView, this.mapView.getDimension())); + } + else if (this.optionsLabel.posWithin(x, y)) + { + try + { + GuiScreen newScreen = ModGuiConfig.class.getConstructor(GuiScreen.class).newInstance(this); this.mc.displayGuiScreen(newScreen); - } catch (Exception e) { - Logging.logError( - "There was a critical issue trying to build the config GUI for %s", - Reference.MOD_ID); } - } else if (this.updateLabel.posWithin(x, y)) { + catch (Exception e) + { + Logging.logError("There was a critical issue trying to build the config GUI for %s", Reference.MOD_ID); + } + } + else if (this.updateLabel.posWithin(x, y)) + { URI uri; - - if (!this.mc.gameSettings.chatLinks) { + + if (!this.mc.gameSettings.chatLinks) + { return; } - - try { + + try + { uri = new URI(VersionCheck.getUpdateURL()); - - if (!Reference.PROTOCOLS.contains(uri.getScheme().toLowerCase())) { - throw new URISyntaxException(uri.toString(), - "Unsupported protocol: " - + uri.getScheme().toLowerCase()); + + if (!Reference.PROTOCOLS.contains(uri.getScheme().toLowerCase())) + { + throw new URISyntaxException(uri.toString(), "Unsupported protocol: " + uri.getScheme().toLowerCase()); } - - if (this.mc.gameSettings.chatLinksPrompt) { + + if (this.mc.gameSettings.chatLinksPrompt) + { this.clickedLinkURI = uri; - this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, - uri.toString(), 31102009, false)); - } else { + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, uri.toString(), 31102009, false)); + } + else + { Utils.openWebLink(uri); } - } catch (URISyntaxException urisyntaxexception) { - Logging.logError("Can\'t open url for %s", - urisyntaxexception); } - } else { + catch (URISyntaxException urisyntaxexception) + { + Logging.logError("Can\'t open url for %s", urisyntaxexception); + } + } + else + { this.mouseLeftHeld = 1; this.mouseLeftDragStartX = x; this.mouseLeftDragStartY = y; this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { + + if ((marker != null) && (prevMarker == marker)) + { // clicked previously selected marker. // start moving the marker. this.movingMarker = marker; @@ -544,21 +495,24 @@ protected void mouseClicked(int x, int y, int button) { this.movingMarkerZStart = marker.z; } } - - } else if (button == 1) { + + } + else if (button == 1) + { this.openMarkerGui(marker, x, y); } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, - y); - + + else if (button == 2) + { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), - blockPoint.x, blockPoint.y, this.mapView); + { + provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); + } } - + this.viewXStart = this.mapView.getX(); this.viewZStart = this.mapView.getZ(); // this.viewSizeStart = this.mapManager.getViewSize(); @@ -567,92 +521,121 @@ else if (button == 2) { // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB // not called on mouse movement. - protected void mouseReleased(int x, int y, int button) { + @Override + protected void mouseReleased(int x, int y, int button) + { // MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { + if (button == 0) + { this.mouseLeftHeld = 0; this.movingMarker = null; - } else if (button == 1) { + } + else if (button == 1) + { // this.mouseRightHeld = 0; } } // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { + public void mouseDWheelScrolled(int x, int y, int direction) + { Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) - && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { + if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) + { + if (direction > 0) + { marker.colourNext(); - } else { + } + else + { marker.colourPrev(); } - } else if (this.dimensionLabel.posWithin(x, y)) { + } + else if (this.dimensionLabel.posWithin(x, y)) + { int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, - n); + this.mapView.nextDimension(WorldConfig.getInstance().dimensionList, n); - } else if (this.groupLabel.posWithin(x, y)) { + } + else if (this.groupLabel.posWithin(x, y)) + { int n = (direction > 0) ? 1 : -1; this.mw.markerManager.nextGroup(n); this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { + } + else if (this.overlayLabel.posWithin(x, y)) + { int n = (direction > 0) ? 1 : -1; if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated( - this.mapView); + { + MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); + } if (n == 1) + { MwAPI.setNextProvider(); + } else + { MwAPI.setPrevProvider(); + } if (MwAPI.getCurrentDataProvider() != null) + { MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + } - } else { + } + else + { int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, - this.mouseBlockX, this.mouseBlockZ); + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); Config.fullScreenZoomLevel = this.mapView.getZoomLevel(); } } - //closes this gui + // closes this gui public void exitGui() { - this.mc.displayGuiScreen((GuiScreen)null); + this.mc.displayGuiScreen((GuiScreen) null); } - - /** - * Called when the screen is unloaded. Used to disable keyboard repeat events - */ - public void onGuiClosed() - { - Keyboard.enableRepeatEvents(false); + + /** + * Called when the screen is unloaded. Used to disable keyboard repeat + * events + */ + @Override + public void onGuiClosed() + { + Keyboard.enableRepeatEvents(false); this.mw.miniMap.view.setDimension(this.mapView.getDimension()); Keyboard.enableRepeatEvents(false); - } - + } + // called every frame - public void updateScreen() + @Override + public void updateScreen() { } - public void drawStatus(int bX, int bY, int bZ) + public void drawStatus(int bX, int bY, int bZ) { StringBuilder builder = new StringBuilder(); - if (bY != 0) { + if (bY != 0) + { builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ)); - } else { + } + else + { builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ)); } - - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) + + if (this.mc.theWorld != null) + { + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) { - builder.append(", " ); + builder.append(", "); builder.append(I18n.format("mw.gui.mwgui.status.biome", new Object[0])); builder.append(String.format(": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); } @@ -664,41 +647,45 @@ public void drawStatus(int bX, int bY, int bZ) builder.append(provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ)); } String s = builder.toString(); - int x = this.width / 2 - 10 - (this.fontRendererObj.getStringWidth(s)/ 2); - + int x = (this.width / 2) - 10 - (this.fontRendererObj.getStringWidth(s) / 2); + this.statusLabel.setCoords(x, this.height - 21); - this.statusLabel.setText(new String[]{builder.toString()}, null); - statusLabel.draw(); + this.statusLabel.setText(new String[] + { + builder.toString() + }, null); + this.statusLabel.draw(); } // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { + @Override + public void drawScreen(int mouseX, int mouseY, float f) + { this.drawDefaultBackground(); double xOffset = 0.0; double yOffset = 0.0; // double zoomFactor = 1.0; - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) - * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) - * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView - .getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, - this.viewZStart + yOffset); + if (this.mouseLeftHeld > 2) + { + xOffset = ((this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth()) / this.mapMode.w; + yOffset = ((this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight()) / this.mapMode.h; + + if (this.movingMarker != null) + { + double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); + } + else + { + this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); } } - if (this.mouseLeftHeld > 0) { + if (this.mouseLeftHeld > 0) + { this.mouseLeftHeld++; } @@ -712,10 +699,9 @@ public void drawScreen(int mouseX, int mouseY, float f) { Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); this.mouseBlockX = p.x; this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, - this.mouseBlockZ); + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); - //draw the label near mousepointer + // draw the label near mousepointer this.drawMarkerLabel(mouseX, mouseY, f); // draw status message @@ -724,8 +710,9 @@ public void drawScreen(int mouseX, int mouseY, float f) { // draw labels this.drawLabel(mouseX, mouseY, f); - MarkerOverlay.drawScreen(mouseX, mouseY, f);; - + this.MarkerOverlay.drawScreen(mouseX, mouseY, f); + ; + super.drawScreen(mouseX, mouseY, f); } @@ -733,74 +720,79 @@ private void drawMarkerLabel(int mouseX, int mouseY, float f) { // draw name of marker under mouse cursor Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - markerLabel.setText( - new String[]{ - marker.name, - String.format("(%d, %d, %d)", - marker.x, - marker.y, - marker.z) - }, - null - ); - markerLabel.setCoords(mouseX + 8, mouseY); - markerLabel.draw(); + if (marker != null) + { + this.markerLabel.setText(new String[] + { + marker.name, + String.format("(%d, %d, %d)", marker.x, marker.y, marker.z) + }, null); + this.markerLabel.setCoords(mouseX + 8, mouseY); + this.markerLabel.draw(); } // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - markerLabel.setText( - new String[]{ - this.mc.thePlayer.getDisplayNameString(), - String.format("(%d, %d, %d)", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt) - }, - null - ); - markerLabel.setCoords(mouseX + 8, mouseY); - markerLabel.draw(); - } + if (this.isPlayerNearScreenPos(mouseX, mouseY)) + { + this.markerLabel.setText(new String[] + { + this.mc.thePlayer.getDisplayNameString(), + String.format("(%d, %d, %d)", this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt) + }, null); + this.markerLabel.setCoords(mouseX + 8, mouseY); + this.markerLabel.draw(); + } } private void drawLabel(int mouseX, int mouseY, float f) { this.helpLabel.draw(); this.optionsLabel.draw(); - String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", - this.mapView.getDimension()); - this.dimensionLabel.setText(new String[]{dimString}, null); + String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); + this.dimensionLabel.setText(new String[] + { + dimString + }, null); this.dimensionLabel.draw(); - - String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", - this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.setText(new String[]{groupString}, null); + + String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.setText(new String[] + { + groupString + }, null); this.groupLabel.draw(); - - String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", - MwAPI.getCurrentProviderName()); - this.overlayLabel.setText(new String[]{overlayString}, null); + + String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); + this.overlayLabel.setText(new String[] + { + overlayString + }, null); this.overlayLabel.draw(); - - if (!VersionCheck.isLatestVersion()) { - + + if (!VersionCheck.isLatestVersion()) + { + this.updateLabel.draw(); } // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - helpTooltipLabel.draw(); + if (this.helpLabel.posWithin(mouseX, mouseY)) + { + this.helpTooltipLabel.draw(); } - if (this.updateLabel.posWithin(mouseX, mouseY)) { - updateTooltipLabel.draw(); + if (this.updateLabel.posWithin(mouseX, mouseY)) + { + this.updateTooltipLabel.draw(); } } - - public void confirmClicked(boolean result, int id) { - if (id == 31102009) { - if (result) { + + @Override + public void confirmClicked(boolean result, int id) + { + if (id == 31102009) + { + if (result) + { Utils.openWebLink(this.clickedLinkURI); } @@ -811,72 +803,61 @@ public void confirmClicked(boolean result, int id) { public void centerOnSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, 0); + if (this.mw.markerManager.selectedMarker != null) + { + this.mapView.setViewCentreScaled(this.mw.markerManager.selectedMarker.x, this.mw.markerManager.selectedMarker.z, 0); } } - + public void openMarkerGui(Marker m, int mouseX, int mouseY) { - if ((m != null) && (this.mw.markerManager.selectedMarker == m)) { + if ((m != null) && (this.mw.markerManager.selectedMarker == m)) + { // right clicked previously selected marker. // edit the marker if (Config.newMarkerDialog) - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialogNew(this, - this.mw.markerManager, m - ) - ); - } - else - { - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, m)); - } - - } else if (m == null) { + { + this.mc.displayGuiScreen(new MwGuiMarkerDialogNew(this, this.mw.markerManager, m)); + } + else + { + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, this.mw.markerManager, m)); + } + + } + else if (m == null) + { // open new marker dialog String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { + if (group.equals("none")) + { group = I18n.format("mw.gui.mwgui.group", new Object[0]); } int mx, my, mz; - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + if (this.isPlayerNearScreenPos(mouseX, mouseY)) + { // marker at player's locations mx = this.mw.playerXInt; my = this.mw.playerYInt; mz = this.mw.playerZInt; - } else { + } + else + { // marker at mouse pointer location mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY - : Config.defaultTeleportHeight; + my = (this.mouseBlockY > 0) ? this.mouseBlockY : Config.defaultTeleportHeight; mz = this.mouseBlockZ; } - if (Config.newMarkerDialog) - { - this.mc.displayGuiScreen( - new MwGuiMarkerDialogNew( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - else - { - this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, - this.mw.markerManager, "", group, mx, my, mz, - this.mapView.getDimension())); + if (Config.newMarkerDialog) + { + this.mc.displayGuiScreen(new MwGuiMarkerDialogNew(this, this.mw.markerManager, "", group, mx, my, mz, this.mapView.getDimension())); + } + else + { + this.mc.displayGuiScreen(new MwGuiMarkerDialog(this, this.mw.markerManager, "", group, mx, my, mz, this.mapView.getDimension())); + } } } - } } diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java index cb2277e4..d509171c 100644 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -1,40 +1,41 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import mapwriter.config.WorldConfig; -import mapwriter.map.MapView; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiDimensionDialog extends MwGuiTextDialog { - - final Mw mw; - final MapView mapView; - final int dimension; - - public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) { - super(parentScreen, - I18n.format("mw.gui.mwguidimensiondialog.title", new Object[0]) + ":", - Integer.toString(dimension), - I18n.format("mw.gui.mwguidimensiondialog.error", new Object[0])); - this.mw = mw; - this.mapView = mapView; - this.dimension = dimension; - } - - @Override - public boolean submit() { - boolean done = false; - int dimension = this.getInputAsInt(); - if (this.inputValid) { - this.mapView.setDimensionAndAdjustZoom(dimension); - this.mw.miniMap.view.setDimension(dimension); - WorldConfig.getInstance().addDimension(dimension); - done = true; - } - return done; - } -} +package mapwriter.gui; + +import mapwriter.Mw; +import mapwriter.config.WorldConfig; +import mapwriter.map.MapView; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiDimensionDialog extends MwGuiTextDialog +{ + + final Mw mw; + final MapView mapView; + final int dimension; + + public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) + { + super(parentScreen, I18n.format("mw.gui.mwguidimensiondialog.title", new Object[0]) + ":", Integer.toString(dimension), I18n.format("mw.gui.mwguidimensiondialog.error", new Object[0])); + this.mw = mw; + this.mapView = mapView; + this.dimension = dimension; + } + + @Override + public boolean submit() + { + boolean done = false; + int dimension = this.getInputAsInt(); + if (this.inputValid) + { + this.mapView.setDimensionAndAdjustZoom(dimension); + this.mw.miniMap.view.setDimension(dimension); + WorldConfig.getInstance().addDimension(dimension); + done = true; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiLabel.java b/src/main/java/mapwriter/gui/MwGuiLabel.java index 41b09f51..a1b76e27 100644 --- a/src/main/java/mapwriter/gui/MwGuiLabel.java +++ b/src/main/java/mapwriter/gui/MwGuiLabel.java @@ -5,199 +5,211 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; -public class MwGuiLabel +public class MwGuiLabel { - int x = 0, y = 0, w = 1, h = 12; - static int spacingX = 4; - static int spacingY = 2; - private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; - private Boolean Background; - private Boolean AllowFlip; - private int parentWidth; - private int parentHeight; - private String str1; - private String str2; - private String[] s1; - private String[] s2; - - private MwGuiLabel label; - private Side side = Side.none; - - private enum Side - { - left,right,top,bottom,none - } - - public MwGuiLabel(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) - { - this.Background = Background; - this.AllowFlip = AllowFlip; - - this.parentWidth = parentWidth; - this.parentHeight = parentHeight; - - this.setCoords(x, y); - this.setText(s1, s2); - } - - public void draw() - { - this.updateCoords(); - if (str1 != null) - { - if(Background) - { - Gui.drawRect(this.x - spacingX, this.y - this.spacingY, this.x + this.w + this.spacingX, this.h + this.y + this.spacingY, 0x80000000); - } - - this.fontRendererObj.drawSplitString(str1, this.x , this.y, this.w, 0xffffff); - - if (this.str2 != null) - { - this.fontRendererObj.drawSplitString(str2, this.x + 65, this.y, this.w, 0xffffff); - } - } - } - - public void drawToRightOf(MwGuiLabel label) - { - this.label = label; - this.side = Side.right; - } - - public void drawToLeftOf(MwGuiLabel label) { - this.label = label; - this.side = Side.left; - } - - public void drawToBelowOf(MwGuiLabel label) { - this.label = label; - this.side = Side.bottom; - } - - public void drawToAboveOf(MwGuiLabel label) { - this.label = label; - this.side = Side.top; - } - - private void updateCoords() - { - switch (this.side) { - case left: - this.setCoords(this.label.x - (this.w + (2 * spacingX) + 2), this.label.y); - break; - - case right: - this.setCoords(this.label.x + this.label.w + (2 * spacingX) + 2, this.label.y); - break; - - case bottom: - this.setCoords(this.label.x, this.label.y + this.label.h + (2 * spacingY) + 2); - break; - - case top: - this.setCoords(this.label.x, this.label.y - (this.h + (2 * spacingY) + 2)); - break; - - default: - break; - } - } - - public boolean posWithin(int x, int y) { - return (x >= this.x + spacingX) && (y >= this.y + spacingY) && (x <= (this.x + this.w + spacingX)) && (y <= (this.y + this.h + spacingY)); - } - - public void setDrawBackground(boolean enable) - { - Background = enable; - } - public boolean getDrawBackground() - { - return Background; - } - - public void setAllowFlip(boolean enable) - { - Background = enable; - } - public boolean getAllowFlip() - { - return Background; - } - - public int getparentWidth() - { - return parentWidth; - } - - public int getparentHeight() - { - return parentHeight; - } - - public void setCoords(int x, int y) - { - if (AllowFlip) - { - if (x + this.w + this.spacingX > this.parentWidth) - { - this.x = x - this.w - this.spacingX - 5; - } - else - { - this.x = x; - } - if (y + this.h + this.spacingY > this.parentHeight) - { - this.y = y - this.h - this.spacingY; - } - else - { - this.y = y; - } - } - else - { - this.x = x; - this.y = y; - } - } - - public void setParentWidthAndHeight(int width, int height) - { - this.parentWidth = width; - this.parentHeight = height; - - this.updateWidthAndHeight(); - } - - public void setText(String[] s1, String[] s2) - { - this.s1 = s1; - this.s2 = s2; - this.UpdateStrings(); - } - - private void UpdateStrings() - { - if (s1 != null && s1.length >0) - { - str1 = Utils.stringArrayToString(this.s1); - } - if (s2 != null && s2.length >0) - { - str2 = Utils.stringArrayToString(this.s2); - } - this.updateWidthAndHeight(); - } - private void updateWidthAndHeight() - { - if (s1 != null) - { - int stringwidth = Utils.getMaxWidth(s1, s2); - this.w = stringwidth < parentWidth - 20 ? stringwidth : parentWidth - 20; - this.h = fontRendererObj.splitStringWidth(str1, parentWidth > 0 ? parentWidth : 10); - } - } + int x = 0, y = 0, w = 1, h = 12; + static int spacingX = 4; + static int spacingY = 2; + private FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj;; + private Boolean Background; + private Boolean AllowFlip; + private int parentWidth; + private int parentHeight; + private String str1; + private String str2; + private String[] s1; + private String[] s2; + + private MwGuiLabel label; + private Side side = Side.none; + + private enum Side + { + left, + right, + top, + bottom, + none + } + + public MwGuiLabel(String[] s1, String[] s2, int x, int y, Boolean Background, Boolean AllowFlip, int parentWidth, int parentHeight) + { + this.Background = Background; + this.AllowFlip = AllowFlip; + + this.parentWidth = parentWidth; + this.parentHeight = parentHeight; + + this.setCoords(x, y); + this.setText(s1, s2); + } + + public void draw() + { + this.updateCoords(); + if (this.str1 != null) + { + if (this.Background) + { + Gui.drawRect(this.x - spacingX, this.y - MwGuiLabel.spacingY, this.x + this.w + MwGuiLabel.spacingX, this.h + this.y + MwGuiLabel.spacingY, 0x80000000); + } + + this.fontRendererObj.drawSplitString(this.str1, this.x, this.y, this.w, 0xffffff); + + if (this.str2 != null) + { + this.fontRendererObj.drawSplitString(this.str2, this.x + 65, this.y, this.w, 0xffffff); + } + } + } + + public void drawToRightOf(MwGuiLabel label) + { + this.label = label; + this.side = Side.right; + } + + public void drawToLeftOf(MwGuiLabel label) + { + this.label = label; + this.side = Side.left; + } + + public void drawToBelowOf(MwGuiLabel label) + { + this.label = label; + this.side = Side.bottom; + } + + public void drawToAboveOf(MwGuiLabel label) + { + this.label = label; + this.side = Side.top; + } + + private void updateCoords() + { + switch (this.side) + { + case left: + this.setCoords(this.label.x - (this.w + (2 * spacingX) + 2), this.label.y); + break; + + case right: + this.setCoords(this.label.x + this.label.w + (2 * spacingX) + 2, this.label.y); + break; + + case bottom: + this.setCoords(this.label.x, this.label.y + this.label.h + (2 * spacingY) + 2); + break; + + case top: + this.setCoords(this.label.x, this.label.y - (this.h + (2 * spacingY) + 2)); + break; + + default: + break; + } + } + + public boolean posWithin(int x, int y) + { + return (x >= (this.x + spacingX)) && (y >= (this.y + spacingY)) && (x <= (this.x + this.w + spacingX)) && (y <= (this.y + this.h + spacingY)); + } + + public void setDrawBackground(boolean enable) + { + this.Background = enable; + } + + public boolean getDrawBackground() + { + return this.Background; + } + + public void setAllowFlip(boolean enable) + { + this.Background = enable; + } + + public boolean getAllowFlip() + { + return this.Background; + } + + public int getparentWidth() + { + return this.parentWidth; + } + + public int getparentHeight() + { + return this.parentHeight; + } + + public void setCoords(int x, int y) + { + if (this.AllowFlip) + { + if ((x + this.w + MwGuiLabel.spacingX) > this.parentWidth) + { + this.x = x - this.w - MwGuiLabel.spacingX - 5; + } + else + { + this.x = x; + } + if ((y + this.h + MwGuiLabel.spacingY) > this.parentHeight) + { + this.y = y - this.h - MwGuiLabel.spacingY; + } + else + { + this.y = y; + } + } + else + { + this.x = x; + this.y = y; + } + } + + public void setParentWidthAndHeight(int width, int height) + { + this.parentWidth = width; + this.parentHeight = height; + + this.updateWidthAndHeight(); + } + + public void setText(String[] s1, String[] s2) + { + this.s1 = s1; + this.s2 = s2; + this.UpdateStrings(); + } + + private void UpdateStrings() + { + if ((this.s1 != null) && (this.s1.length > 0)) + { + this.str1 = Utils.stringArrayToString(this.s1); + } + if ((this.s2 != null) && (this.s2.length > 0)) + { + this.str2 = Utils.stringArrayToString(this.s2); + } + this.updateWidthAndHeight(); + } + + private void updateWidthAndHeight() + { + if (this.s1 != null) + { + int stringwidth = Utils.getMaxWidth(this.s1, this.s2); + this.w = stringwidth < (this.parentWidth - 20) ? stringwidth : this.parentWidth - 20; + this.h = this.fontRendererObj.splitStringWidth(this.str1, this.parentWidth > 0 ? this.parentWidth : 10); + } + } } diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java index 65b67ec6..e558abb1 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -1,113 +1,116 @@ -package mapwriter.gui; - -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.util.Utils; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiMarkerDialog extends MwGuiTextDialog { - private final MarkerManager markerManager; - private Marker editingMarker; - private String markerName = ""; - private String markerGroup = ""; - private int markerX = 0; - private int markerY = 80; - private int markerZ = 0; - private int state = 0; - private int dimension = 0; - - public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { - super(parentScreen, - I18n.format("mw.gui.mwguimarkerdialog.title.new", new Object[0]) + ":", - markerName, - I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); - this.markerManager = markerManager; - this.markerName = markerName; - this.markerGroup = markerGroup; - this.markerX = x; - this.markerY = y; - this.markerZ = z; - this.editingMarker = null; - this.dimension = dimension; - } - - public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) { - super(parentScreen, - I18n.format("mw.gui.mwguimarkerdialog.title.edit", new Object[0]) + ":", - editingMarker.name, - I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); - this.markerManager = markerManager; - this.editingMarker = editingMarker; - this.markerName = editingMarker.name; - this.markerGroup = editingMarker.groupName; - this.markerX = editingMarker.x; - this.markerY = editingMarker.y; - this.markerZ = editingMarker.z; - this.dimension = editingMarker.dimension; - } - - @Override - public boolean submit() { - boolean done = false; - switch(this.state) { - case 0: - this.markerName = this.getInputAsString(); - if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.group", new Object[0]) + ":"; - this.setText(this.markerGroup); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.group", new Object[0]); - this.state++; - } - break; - case 1: - this.markerGroup = this.getInputAsString(); - if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.x", new Object[0]) + ":"; - this.setText("" + this.markerX); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.x", new Object[0]); - this.state++; - } - break; - case 2: - this.markerX = this.getInputAsInt(); - if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.y", new Object[0]) + ":"; - this.setText("" + this.markerY); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.y", new Object[0]); - this.state++; - } - break; - case 3: - this.markerY = this.getInputAsInt(); - if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.z", new Object[0]) + ":"; - this.setText("" + this.markerZ); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.z", new Object[0]); - this.state++; - } - break; - case 4: - this.markerZ = this.getInputAsInt(); - if (this.inputValid) { - done = true; - int colour = Utils.getCurrentColour(); - if (this.editingMarker != null) { - colour = this.editingMarker.colour; - this.markerManager.delMarker(this.editingMarker); - this.editingMarker = null; - } - this.markerManager.addMarker(this.markerName, this.markerGroup, - this.markerX, this.markerY, this.markerZ, - this.dimension, colour); - this.markerManager.setVisibleGroupName(this.markerGroup); - this.markerManager.update(); - } - break; - } - return done; - } -} +package mapwriter.gui; + +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.util.Utils; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiMarkerDialog extends MwGuiTextDialog +{ + private final MarkerManager markerManager; + private Marker editingMarker; + private String markerName = ""; + private String markerGroup = ""; + private int markerX = 0; + private int markerY = 80; + private int markerZ = 0; + private int state = 0; + private int dimension = 0; + + public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) + { + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.new", new Object[0]) + ":", markerName, I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); + this.markerManager = markerManager; + this.markerName = markerName; + this.markerGroup = markerGroup; + this.markerX = x; + this.markerY = y; + this.markerZ = z; + this.editingMarker = null; + this.dimension = dimension; + } + + public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) + { + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.edit", new Object[0]) + ":", editingMarker.name, I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); + this.markerManager = markerManager; + this.editingMarker = editingMarker; + this.markerName = editingMarker.name; + this.markerGroup = editingMarker.groupName; + this.markerX = editingMarker.x; + this.markerY = editingMarker.y; + this.markerZ = editingMarker.z; + this.dimension = editingMarker.dimension; + } + + @Override + public boolean submit() + { + boolean done = false; + switch (this.state) + { + case 0: + this.markerName = this.getInputAsString(); + if (this.inputValid) + { + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.group", new Object[0]) + ":"; + this.setText(this.markerGroup); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.group", new Object[0]); + this.state++; + } + break; + case 1: + this.markerGroup = this.getInputAsString(); + if (this.inputValid) + { + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.x", new Object[0]) + ":"; + this.setText("" + this.markerX); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.x", new Object[0]); + this.state++; + } + break; + case 2: + this.markerX = this.getInputAsInt(); + if (this.inputValid) + { + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.y", new Object[0]) + ":"; + this.setText("" + this.markerY); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.y", new Object[0]); + this.state++; + } + break; + case 3: + this.markerY = this.getInputAsInt(); + if (this.inputValid) + { + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.z", new Object[0]) + ":"; + this.setText("" + this.markerZ); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.z", new Object[0]); + this.state++; + } + break; + case 4: + this.markerZ = this.getInputAsInt(); + if (this.inputValid) + { + done = true; + int colour = Utils.getCurrentColour(); + if (this.editingMarker != null) + { + colour = this.editingMarker.colour; + this.markerManager.delMarker(this.editingMarker); + this.editingMarker = null; + } + this.markerManager.addMarker(this.markerName, this.markerGroup, this.markerX, this.markerY, this.markerZ, this.dimension, colour); + this.markerManager.setVisibleGroupName(this.markerGroup); + this.markerManager.update(); + } + break; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index 796e6536..522bb653 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -1,392 +1,341 @@ -package mapwriter.gui; - -import java.io.IOException; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import mapwriter.util.Utils; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.relauncher.Side; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -@net.minecraftforge.fml.relauncher.SideOnly(Side.CLIENT) -public class MwGuiMarkerDialogNew extends GuiScreen { - private final GuiScreen parentScreen; - String title = ""; - String titleNew = "mw.gui.mwguimarkerdialognew.title.new"; - String titleEdit = "mw.gui.mwguimarkerdialognew.title.edit"; - private String editMarkerName = "mw.gui.mwguimarkerdialognew.editMarkerName"; - private String editMarkerGroup = "mw.gui.mwguimarkerdialognew.editMarkerGroup"; - private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; - private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; - private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; - private String editMarkerColor = "mw.gui.mwguimarkerdialognew.editMarkerColor"; - ScrollableTextBox scrollableTextBoxName = null; - ScrollableTextBox scrollableTextBoxGroup = null; - ScrollableNumericTextBox scrollableNumericTextBoxX = null; - ScrollableNumericTextBox scrollableNumericTextBoxY = null; - ScrollableNumericTextBox scrollableNumericTextBoxZ = null; - ScrollableColorSelector ScrollableColorSelectorColor = null; - boolean backToGameOnSubmit = false; - static final int dialogWidthPercent = 40; - static final int elementVSpacing = 20; - static final int numberOfElements = 8; - private final MarkerManager markerManager; - private Marker editingMarker; - private String markerName = ""; - private String markerGroup = ""; - private int markerX = 0; - private int markerY = 80; - private int markerZ = 0; - private int dimension = 0; - private int colour = 0; - - - public MwGuiMarkerDialogNew( - GuiScreen parentScreen, - MarkerManager markerManager, - String markerName, - String markerGroup, - int x, - int y, - int z, - int dimension - ) - { - this.markerManager = markerManager; - this.markerName = markerName; - this.markerGroup = markerGroup; - this.markerX = x; - this.markerY = y; - this.markerZ = z; - this.dimension = dimension; - this.colour = Utils.getCurrentColour(); - this.editingMarker = null; - this.parentScreen = parentScreen; - this.title = this.titleNew; - } - - public MwGuiMarkerDialogNew( - GuiScreen parentScreen, - MarkerManager markerManager, - Marker editingMarker - ) - { - this.markerManager = markerManager; - this.editingMarker = editingMarker; - this.markerName = editingMarker.name; - this.markerGroup = editingMarker.groupName; - this.markerX = editingMarker.x; - this.markerY = editingMarker.y; - this.markerZ = editingMarker.z; - this.dimension = editingMarker.dimension; - this.colour = editingMarker.colour; - this.parentScreen = parentScreen; - this.title = this.titleEdit; - } - - public boolean submit() { - boolean inputCorrect = true; - - if (scrollableTextBoxName.validateTextFieldData()) - { - this.markerName = scrollableTextBoxName.getText(); - } - else - { - inputCorrect = false; - } - - if (scrollableTextBoxGroup.validateTextFieldData()) - { - this.markerGroup = scrollableTextBoxGroup.getText(); - } - else - { - inputCorrect = false; - } - - if (scrollableNumericTextBoxX.validateTextFieldData()) - { - this.markerX = scrollableNumericTextBoxX.getTextFieldIntValue(); - } - else - { - inputCorrect = false; - } - - if (scrollableNumericTextBoxY.validateTextFieldData()) - { - this.markerY = scrollableNumericTextBoxY.getTextFieldIntValue(); - } - else - { - inputCorrect = false; - } - - if (scrollableNumericTextBoxZ.validateTextFieldData()) - { - this.markerZ = scrollableNumericTextBoxZ.getTextFieldIntValue(); - } - else - { - inputCorrect = false; - } - - if (ScrollableColorSelectorColor.validateColorData()) - { - this.colour = ScrollableColorSelectorColor.getColor(); - } - else - { - inputCorrect = false; - } - - if (inputCorrect) - { - if (this.editingMarker != null) - { - this.markerManager.delMarker(this.editingMarker); - this.editingMarker = null; - } - this.markerManager.addMarker( - this.markerName, - this.markerGroup, - this.markerX, - this.markerY, - this.markerZ, - this.dimension, - this.colour - ); - this.markerManager.setVisibleGroupName(this.markerGroup); - this.markerManager.update(); - } - return inputCorrect; - } - - public void initGui() { - int labelsWidth = this.fontRendererObj.getStringWidth("Group"); - int width = (this.width * dialogWidthPercent / 100) - labelsWidth - 20; - int x = (this.width - width + labelsWidth) / 2; - int y = (this.height - elementVSpacing * numberOfElements) / 2; - - this.scrollableTextBoxName = new ScrollableTextBox( - x, - y, - width, - I18n.format(this.editMarkerName, new Object[0]), - this.fontRendererObj - ); - this.scrollableTextBoxName.setFocused(true); - this.scrollableTextBoxName.setText(this.markerName); - - this.scrollableTextBoxGroup = new ScrollableTextBox( - x, - y + MwGuiMarkerDialogNew.elementVSpacing, - width, - I18n.format(this.editMarkerGroup, new Object[0]), - this.markerManager.groupList, - this.fontRendererObj - ); - this.scrollableTextBoxGroup.setText(this.markerGroup); - this.scrollableTextBoxGroup.setDrawArrows(true); - - this.scrollableNumericTextBoxX = new ScrollableNumericTextBox( - x, - y + MwGuiMarkerDialogNew.elementVSpacing * 2, - width, - I18n.format(this.editMarkerX, new Object[0]), - this.fontRendererObj - ); - this.scrollableNumericTextBoxX.setText("" + this.markerX); - this.scrollableNumericTextBoxX.setDrawArrows(true); - - this.scrollableNumericTextBoxY = new ScrollableNumericTextBox( - x, - y + MwGuiMarkerDialogNew.elementVSpacing * 3, - width, - I18n.format(this.editMarkerY, new Object[0]), - this.fontRendererObj - ); - this.scrollableNumericTextBoxY.setText("" + this.markerY); - this.scrollableNumericTextBoxY.setDrawArrows(true); - - this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox( - x, - y + MwGuiMarkerDialogNew.elementVSpacing * 4, - width, - I18n.format(this.editMarkerZ, new Object[0]), - this.fontRendererObj - ); - this.scrollableNumericTextBoxZ.setText("" + this.markerZ); - this.scrollableNumericTextBoxZ.setDrawArrows(true); - - this.ScrollableColorSelectorColor = new ScrollableColorSelector( - x, - y + MwGuiMarkerDialogNew.elementVSpacing * 5, - width, - I18n.format(this.editMarkerColor, new Object[0]), - this.fontRendererObj - ); - this.ScrollableColorSelectorColor.setColor(this.colour); - this.ScrollableColorSelectorColor.setDrawArrows(true); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float f) { - if (this.parentScreen != null) { - this.parentScreen.drawScreen(mouseX, mouseY, f); - } else { - this.drawDefaultBackground(); - } - - int w = this.width * MwGuiMarkerDialogNew.dialogWidthPercent / 100; - drawRect( - (this.width - w) / 2, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2)) / 2 - 4, - (this.width - w) / 2 + w, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2)) / 2 - + MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1), - 0x80000000); - this.drawCenteredString( - this.fontRendererObj, - I18n.format(this.title, new Object[0]), - (this.width) / 2, - (this.height - MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1)) / 2 - - MwGuiMarkerDialogNew.elementVSpacing / 4, - 0xffffff); - this.scrollableTextBoxName.draw(); - this.scrollableTextBoxGroup.draw(); - this.scrollableNumericTextBoxX.draw(); - this.scrollableNumericTextBoxY.draw(); - this.scrollableNumericTextBoxZ.draw(); - this.ScrollableColorSelectorColor.draw(); - super.drawScreen(mouseX, mouseY, f); - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() throws IOException { - if (MwAPI.getCurrentDataProvider() != null) - return; - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height - / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - public void mouseDWheelScrolled(int x, int y, int direction) { - this.scrollableTextBoxName.mouseDWheelScrolled(x, y, direction); - this.scrollableTextBoxGroup.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxX.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxY.mouseDWheelScrolled(x, y, direction); - this.scrollableNumericTextBoxZ.mouseDWheelScrolled(x, y, direction); - this.ScrollableColorSelectorColor.mouseDWheelScrolled(x, y, direction); - } - - protected void mouseClicked(int x, int y, int button) throws IOException { - super.mouseClicked(x, y, button); - - this.scrollableTextBoxName.mouseClicked(x, y, button); - this.scrollableTextBoxGroup.mouseClicked(x, y, button); - this.scrollableNumericTextBoxX.mouseClicked(x, y, button); - this.scrollableNumericTextBoxY.mouseClicked(x, y, button); - this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); - this.ScrollableColorSelectorColor.mouseClicked(x, y, button); - } - - protected void keyTyped(char c, int key) { - switch (key) { - case Keyboard.KEY_ESCAPE: - this.mc.displayGuiScreen(this.parentScreen); - break; - case Keyboard.KEY_RETURN: - // when enter pressed, submit current input - if (this.submit()) - { - if (!this.backToGameOnSubmit) { - this.mc.displayGuiScreen(this.parentScreen); - } else { - this.mc.displayGuiScreen(null); - } - } - break; - case Keyboard.KEY_TAB: - ScrollableField thisField = null; - ScrollableField prevField = null; - ScrollableField nextField = null; - - if (this.scrollableTextBoxName.isFocused()) - { - thisField = scrollableTextBoxName; - prevField = ScrollableColorSelectorColor; - nextField = scrollableTextBoxGroup; - } - else if (this.scrollableTextBoxGroup.isFocused()) - { - thisField = scrollableTextBoxGroup; - prevField = scrollableTextBoxName; - nextField = scrollableNumericTextBoxX; - } - else if (this.scrollableNumericTextBoxX.isFocused()) - { - thisField = scrollableNumericTextBoxX; - prevField = scrollableTextBoxGroup; - nextField = scrollableNumericTextBoxY; - } - else if (this.scrollableNumericTextBoxY.isFocused()) - { - thisField = scrollableNumericTextBoxY; - prevField = scrollableNumericTextBoxX; - nextField = scrollableNumericTextBoxZ; - } - else if (this.scrollableNumericTextBoxZ.isFocused()) - { - thisField = scrollableNumericTextBoxZ; - prevField = scrollableNumericTextBoxY; - nextField = ScrollableColorSelectorColor; - } - else if (this.ScrollableColorSelectorColor.isFocused()) - { - thisField = this.ScrollableColorSelectorColor.thisField(); - nextField = this.ScrollableColorSelectorColor.nextField(scrollableTextBoxName); - prevField = this.ScrollableColorSelectorColor.prevField((ScrollableField)scrollableNumericTextBoxZ); - } - - thisField.setFocused(false); - - if (thisField instanceof ScrollableTextBox) - { - ((ScrollableTextBox)thisField).setCursorPositionEnd(); - } - if (Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)) - { - prevField.setFocused(true); - } - else - { - nextField.setFocused(true); - } - - break; - default: - this.scrollableTextBoxName.KeyTyped(c, key); - this.scrollableTextBoxGroup.KeyTyped(c, key); - this.scrollableNumericTextBoxX.KeyTyped(c, key); - this.scrollableNumericTextBoxY.KeyTyped(c, key); - this.scrollableNumericTextBoxZ.KeyTyped(c, key); - this.ScrollableColorSelectorColor.KeyTyped(c, key); - break; - } - } +package mapwriter.gui; + +import java.io.IOException; + +import mapwriter.api.MwAPI; +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import mapwriter.util.Utils; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.relauncher.Side; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +@net.minecraftforge.fml.relauncher.SideOnly(Side.CLIENT) +public class MwGuiMarkerDialogNew extends GuiScreen +{ + private final GuiScreen parentScreen; + String title = ""; + String titleNew = "mw.gui.mwguimarkerdialognew.title.new"; + String titleEdit = "mw.gui.mwguimarkerdialognew.title.edit"; + private String editMarkerName = "mw.gui.mwguimarkerdialognew.editMarkerName"; + private String editMarkerGroup = "mw.gui.mwguimarkerdialognew.editMarkerGroup"; + private String editMarkerX = "mw.gui.mwguimarkerdialognew.editMarkerX"; + private String editMarkerY = "mw.gui.mwguimarkerdialognew.editMarkerY"; + private String editMarkerZ = "mw.gui.mwguimarkerdialognew.editMarkerZ"; + private String editMarkerColor = "mw.gui.mwguimarkerdialognew.editMarkerColor"; + ScrollableTextBox scrollableTextBoxName = null; + ScrollableTextBox scrollableTextBoxGroup = null; + ScrollableNumericTextBox scrollableNumericTextBoxX = null; + ScrollableNumericTextBox scrollableNumericTextBoxY = null; + ScrollableNumericTextBox scrollableNumericTextBoxZ = null; + ScrollableColorSelector ScrollableColorSelectorColor = null; + boolean backToGameOnSubmit = false; + static final int dialogWidthPercent = 40; + static final int elementVSpacing = 20; + static final int numberOfElements = 8; + private final MarkerManager markerManager; + private Marker editingMarker; + private String markerName = ""; + private String markerGroup = ""; + private int markerX = 0; + private int markerY = 80; + private int markerZ = 0; + private int dimension = 0; + private int colour = 0; + + public MwGuiMarkerDialogNew(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) + { + this.markerManager = markerManager; + this.markerName = markerName; + this.markerGroup = markerGroup; + this.markerX = x; + this.markerY = y; + this.markerZ = z; + this.dimension = dimension; + this.colour = Utils.getCurrentColour(); + this.editingMarker = null; + this.parentScreen = parentScreen; + this.title = this.titleNew; + } + + public MwGuiMarkerDialogNew(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) + { + this.markerManager = markerManager; + this.editingMarker = editingMarker; + this.markerName = editingMarker.name; + this.markerGroup = editingMarker.groupName; + this.markerX = editingMarker.x; + this.markerY = editingMarker.y; + this.markerZ = editingMarker.z; + this.dimension = editingMarker.dimension; + this.colour = editingMarker.colour; + this.parentScreen = parentScreen; + this.title = this.titleEdit; + } + + public boolean submit() + { + boolean inputCorrect = true; + + if (this.scrollableTextBoxName.validateTextFieldData()) + { + this.markerName = this.scrollableTextBoxName.getText(); + } + else + { + inputCorrect = false; + } + + if (this.scrollableTextBoxGroup.validateTextFieldData()) + { + this.markerGroup = this.scrollableTextBoxGroup.getText(); + } + else + { + inputCorrect = false; + } + + if (this.scrollableNumericTextBoxX.validateTextFieldData()) + { + this.markerX = this.scrollableNumericTextBoxX.getTextFieldIntValue(); + } + else + { + inputCorrect = false; + } + + if (this.scrollableNumericTextBoxY.validateTextFieldData()) + { + this.markerY = this.scrollableNumericTextBoxY.getTextFieldIntValue(); + } + else + { + inputCorrect = false; + } + + if (this.scrollableNumericTextBoxZ.validateTextFieldData()) + { + this.markerZ = this.scrollableNumericTextBoxZ.getTextFieldIntValue(); + } + else + { + inputCorrect = false; + } + + if (this.ScrollableColorSelectorColor.validateColorData()) + { + this.colour = this.ScrollableColorSelectorColor.getColor(); + } + else + { + inputCorrect = false; + } + + if (inputCorrect) + { + if (this.editingMarker != null) + { + this.markerManager.delMarker(this.editingMarker); + this.editingMarker = null; + } + this.markerManager.addMarker(this.markerName, this.markerGroup, this.markerX, this.markerY, this.markerZ, this.dimension, this.colour); + this.markerManager.setVisibleGroupName(this.markerGroup); + this.markerManager.update(); + } + return inputCorrect; + } + + @Override + public void initGui() + { + int labelsWidth = this.fontRendererObj.getStringWidth("Group"); + int width = ((this.width * dialogWidthPercent) / 100) - labelsWidth - 20; + int x = ((this.width - width) + labelsWidth) / 2; + int y = (this.height - (elementVSpacing * numberOfElements)) / 2; + + this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); + this.scrollableTextBoxName.setFocused(true); + this.scrollableTextBoxName.setText(this.markerName); + + this.scrollableTextBoxGroup = new ScrollableTextBox(x, y + MwGuiMarkerDialogNew.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), this.markerManager.groupList, this.fontRendererObj); + this.scrollableTextBoxGroup.setText(this.markerGroup); + this.scrollableTextBoxGroup.setDrawArrows(true); + + this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 2), width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxX.setText("" + this.markerX); + this.scrollableNumericTextBoxX.setDrawArrows(true); + + this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 3), width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxY.setText("" + this.markerY); + this.scrollableNumericTextBoxY.setDrawArrows(true); + + this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 4), width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxZ.setText("" + this.markerZ); + this.scrollableNumericTextBoxZ.setDrawArrows(true); + + this.ScrollableColorSelectorColor = new ScrollableColorSelector(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 5), width, I18n.format(this.editMarkerColor, new Object[0]), this.fontRendererObj); + this.ScrollableColorSelectorColor.setColor(this.colour); + this.ScrollableColorSelectorColor.setDrawArrows(true); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) + { + if (this.parentScreen != null) + { + this.parentScreen.drawScreen(mouseX, mouseY, f); + } + else + { + this.drawDefaultBackground(); + } + + int w = (this.width * MwGuiMarkerDialogNew.dialogWidthPercent) / 100; + drawRect((this.width - w) / 2, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2))) / 2) - 4, ((this.width - w) / 2) + w, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2))) / 2) + + (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1)), 0x80000000); + this.drawCenteredString(this.fontRendererObj, I18n.format(this.title, new Object[0]), (this.width) / 2, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1))) / 2) - (MwGuiMarkerDialogNew.elementVSpacing / 4), 0xffffff); + this.scrollableTextBoxName.draw(); + this.scrollableTextBoxGroup.draw(); + this.scrollableNumericTextBoxX.draw(); + this.scrollableNumericTextBoxY.draw(); + this.scrollableNumericTextBoxZ.draw(); + this.ScrollableColorSelectorColor.draw(); + super.drawScreen(mouseX, mouseY, f); + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() throws IOException + { + if (MwAPI.getCurrentDataProvider() != null) + { + return; + } + int x = (Mouse.getEventX() * this.width) / this.mc.displayWidth; + int y = this.height - ((Mouse.getEventY() * this.height) / this.mc.displayHeight) - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) + { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + public void mouseDWheelScrolled(int x, int y, int direction) + { + this.scrollableTextBoxName.mouseDWheelScrolled(x, y, direction); + this.scrollableTextBoxGroup.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxX.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxY.mouseDWheelScrolled(x, y, direction); + this.scrollableNumericTextBoxZ.mouseDWheelScrolled(x, y, direction); + this.ScrollableColorSelectorColor.mouseDWheelScrolled(x, y, direction); + } + + @Override + protected void mouseClicked(int x, int y, int button) throws IOException + { + super.mouseClicked(x, y, button); + + this.scrollableTextBoxName.mouseClicked(x, y, button); + this.scrollableTextBoxGroup.mouseClicked(x, y, button); + this.scrollableNumericTextBoxX.mouseClicked(x, y, button); + this.scrollableNumericTextBoxY.mouseClicked(x, y, button); + this.scrollableNumericTextBoxZ.mouseClicked(x, y, button); + this.ScrollableColorSelectorColor.mouseClicked(x, y, button); + } + + @Override + protected void keyTyped(char c, int key) + { + switch (key) + { + case Keyboard.KEY_ESCAPE: + this.mc.displayGuiScreen(this.parentScreen); + break; + case Keyboard.KEY_RETURN: + // when enter pressed, submit current input + if (this.submit()) + { + if (!this.backToGameOnSubmit) + { + this.mc.displayGuiScreen(this.parentScreen); + } + else + { + this.mc.displayGuiScreen(null); + } + } + break; + case Keyboard.KEY_TAB: + ScrollableField thisField = null; + ScrollableField prevField = null; + ScrollableField nextField = null; + + if (this.scrollableTextBoxName.isFocused()) + { + thisField = this.scrollableTextBoxName; + prevField = this.ScrollableColorSelectorColor; + nextField = this.scrollableTextBoxGroup; + } + else if (this.scrollableTextBoxGroup.isFocused()) + { + thisField = this.scrollableTextBoxGroup; + prevField = this.scrollableTextBoxName; + nextField = this.scrollableNumericTextBoxX; + } + else if (this.scrollableNumericTextBoxX.isFocused()) + { + thisField = this.scrollableNumericTextBoxX; + prevField = this.scrollableTextBoxGroup; + nextField = this.scrollableNumericTextBoxY; + } + else if (this.scrollableNumericTextBoxY.isFocused()) + { + thisField = this.scrollableNumericTextBoxY; + prevField = this.scrollableNumericTextBoxX; + nextField = this.scrollableNumericTextBoxZ; + } + else if (this.scrollableNumericTextBoxZ.isFocused()) + { + thisField = this.scrollableNumericTextBoxZ; + prevField = this.scrollableNumericTextBoxY; + nextField = this.ScrollableColorSelectorColor; + } + else if (this.ScrollableColorSelectorColor.isFocused()) + { + thisField = this.ScrollableColorSelectorColor.thisField(); + nextField = this.ScrollableColorSelectorColor.nextField(this.scrollableTextBoxName); + prevField = this.ScrollableColorSelectorColor.prevField(this.scrollableNumericTextBoxZ); + } + + thisField.setFocused(false); + + if (thisField instanceof ScrollableTextBox) + { + ((ScrollableTextBox) thisField).setCursorPositionEnd(); + } + if (Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)) + { + prevField.setFocused(true); + } + else + { + nextField.setFocused(true); + } + + break; + default: + this.scrollableTextBoxName.KeyTyped(c, key); + this.scrollableTextBoxGroup.KeyTyped(c, key); + this.scrollableNumericTextBoxX.KeyTyped(c, key); + this.scrollableNumericTextBoxY.KeyTyped(c, key); + this.scrollableNumericTextBoxZ.KeyTyped(c, key); + this.ScrollableColorSelectorColor.KeyTyped(c, key); + break; + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java index 60177117..bd846bb4 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -7,29 +7,26 @@ import net.minecraft.client.gui.GuiScreen; public class MwGuiMarkerListOverlay extends MwGuiSlot -{ +{ private final GuiScreen parentScreen; private final MarkerManager markerManager; - + public static int listWidth = 95; public static int ListY = 10; private int height; - private int x; - + public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManager) { - super( - Minecraft.getMinecraft(), //mcIn - listWidth, //width - parentScreen.height - 20, //height - ListY, //topIn - 10 + parentScreen.height - 20, //bottomIn - parentScreen.width - 110 //left + super(Minecraft.getMinecraft(), // mcIn + listWidth, // width + parentScreen.height - 20, // height + ListY, // topIn + (10 + parentScreen.height) - 20, // bottomIn + parentScreen.width - 110 // left ); - - this.x = parentScreen.width - 110; + this.height = parentScreen.height - 20; - + this.parentScreen = parentScreen; this.markerManager = markerManager; } @@ -37,79 +34,75 @@ public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManage @Override protected int getSlotHeight(int index) { - String str = Utils.stringArrayToString(getLabelString(index)); - int height = mc.fontRendererObj.splitStringWidth(str, this.listWidth - 6); - + String str = Utils.stringArrayToString(this.getLabelString(index)); + int height = this.mc.fontRendererObj.splitStringWidth(str, MwGuiMarkerListOverlay.listWidth - 6); + height += this.spacingY * 2; - + return height; } - + protected String[] getLabelString(int index) { - Marker m = markerManager.visibleMarkerList.get(index); - + Marker m = this.markerManager.visibleMarkerList.get(index); + String[] text = new String[2]; - text[0] = m.name; - text[1] = String.format( - "(%d, %d, %d)", - m.x, - m.y, - m.z); + text[0] = m.name; + text[1] = String.format("(%d, %d, %d)", m.x, m.y, m.z); return text; } - + @Override - protected int getSize() + protected int getSize() { - return markerManager.visibleMarkerList.size(); + return this.markerManager.visibleMarkerList.size(); } @Override - protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton) + protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton) { - markerManager.selectedMarker = markerManager.visibleMarkerList.get(slotIndex); + this.markerManager.selectedMarker = this.markerManager.visibleMarkerList.get(slotIndex); if (mouseButton == 1) { - if (parentScreen instanceof MwGui) + if (this.parentScreen instanceof MwGui) { - ((MwGui)parentScreen).openMarkerGui(markerManager.selectedMarker, mouseX, mouseY);; + ((MwGui) this.parentScreen).openMarkerGui(this.markerManager.selectedMarker, mouseX, mouseY); + ; } } - if (mouseButton == 0 && isDoubleClick) + if ((mouseButton == 0) && isDoubleClick) { - if (parentScreen instanceof MwGui) + if (this.parentScreen instanceof MwGui) { - ((MwGui)parentScreen).centerOnSelectedMarker(); + ((MwGui) this.parentScreen).centerOnSelectedMarker(); } } } @Override - protected boolean isSelected(int slotIndex) + protected boolean isSelected(int slotIndex) { - return markerManager.selectedMarker == markerManager.visibleMarkerList.get(slotIndex); + return this.markerManager.selectedMarker == this.markerManager.visibleMarkerList.get(slotIndex); } @Override - protected void drawBackground() - { + protected void drawBackground() + { } - + @Override - protected void drawSlot(int entryID, int x, int y, int slotHeight, int mouseXIn, int mouseYIn) + protected void drawSlot(int entryID, int x, int y, int slotHeight, int mouseXIn, int mouseYIn) { - MwGuiLabel label = new MwGuiLabel(getLabelString(entryID), null, x, y, false, false, this.listWidth, this.height); + MwGuiLabel label = new MwGuiLabel(this.getLabelString(entryID), null, x, y, false, false, MwGuiMarkerListOverlay.listWidth, this.height); label.draw(); } - + @Override - public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) - { - this.x = parentScreen.width - 110; - this.height = parentScreen.height - 20; - - super.setDimensions(widthIn, heightIn, topIn, bottomIn, left); - } + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) + { + this.height = this.parentScreen.height - 20; + + super.setDimensions(widthIn, heightIn, topIn, bottomIn, left); + } } diff --git a/src/main/java/mapwriter/gui/MwGuiSlot.java b/src/main/java/mapwriter/gui/MwGuiSlot.java index 4cc54085..0eaf518b 100644 --- a/src/main/java/mapwriter/gui/MwGuiSlot.java +++ b/src/main/java/mapwriter/gui/MwGuiSlot.java @@ -15,540 +15,548 @@ @SideOnly(Side.CLIENT) public abstract class MwGuiSlot { - protected final Minecraft mc; - public int width; - public int height; - /** The top of the slot container. Affects the overlays and scrolling. */ - public int top; - /** The bottom of the slot container. Affects the overlays and scrolling. */ - public int bottom; - public int right; - public int left; - public final int scrollBarWidth = 6; - /** The buttonID of the button used to scroll up */ - private int scrollUpButtonID; - /** The buttonID of the button used to scroll down */ - private int scrollDownButtonID; - protected int mouseX; - protected int mouseY; - protected boolean field_148163_i = true; - /** Where the mouse was in the window when you first clicked to scroll */ - protected float initialClickY = -2.0F; - /** - * What to multiply the amount you moved your mouse by (used for slowing down scrolling when over the items and not - * on the scroll bar) - */ - protected float scrollMultiplier; - /** How far down this slot has been scrolled */ - protected float amountScrolled; - /** The element in the list that was selected */ - protected int selectedElement = -1; - /** The time when this button was last clicked. */ - protected long lastClicked; - /** Set to true if a selected element in this gui will show an outline box */ - protected boolean showSelectionBox = true; - protected boolean hasListHeader; - public int headerPadding; - private boolean enabled = false; - private static final String __OBFID = "CL_00000679"; + protected final Minecraft mc; + public int width; + public int height; + /** The top of the slot container. Affects the overlays and scrolling. */ + public int top; + /** The bottom of the slot container. Affects the overlays and scrolling. */ + public int bottom; + public int right; + public int left; + public final int scrollBarWidth = 6; + /** The buttonID of the button used to scroll up */ + private int scrollUpButtonID; + /** The buttonID of the button used to scroll down */ + private int scrollDownButtonID; + protected int mouseX; + protected int mouseY; + protected boolean field_148163_i = true; + /** Where the mouse was in the window when you first clicked to scroll */ + protected float initialClickY = -2.0F; + /** + * What to multiply the amount you moved your mouse by (used for slowing + * down scrolling when over the items and not on the scroll bar) + */ + protected float scrollMultiplier; + /** How far down this slot has been scrolled */ + protected float amountScrolled; + /** The element in the list that was selected */ + protected int selectedElement = -1; + /** The time when this button was last clicked. */ + protected long lastClicked; + /** Set to true if a selected element in this gui will show an outline box */ + protected boolean showSelectionBox = true; + protected boolean hasListHeader; + public int headerPadding; + private boolean enabled = false; int spacingY = 4; - - public MwGuiSlot(Minecraft mcIn, int width, int height, int topIn, int bottomIn, int left) - { - this.mc = mcIn; - this.width = width; - this.height = height; - this.top = topIn; - this.bottom = bottomIn; - this.left = left; - this.right = left + width; - } - - public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) - { - this.width = widthIn; - this.height = heightIn; - this.top = topIn; - this.bottom = bottomIn; - this.left = left; - this.right = left + widthIn; - } - - public void setShowSelectionBox(boolean showSelectionBoxIn) - { - this.showSelectionBox = showSelectionBoxIn; - } - - /** - * Sets hasListHeader and headerHeight. Params: hasListHeader, headerHeight. If hasListHeader is false headerHeight - * is set to 0. - */ - protected void setHasListHeader(boolean hasListHeaderIn, int headerPaddingIn) - { - this.hasListHeader = hasListHeaderIn; - this.headerPadding = headerPaddingIn; - - if (!hasListHeaderIn) - { - this.headerPadding = 0; - } - } - - protected abstract int getSize(); - - /** - * The element in the slot that was clicked, boolean for whether it was double clicked or not - */ - protected abstract void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton); - - /** - * Returns true if the element passed in is currently selected - */ - protected abstract boolean isSelected(int slotIndex); - - /** - * - * @param index of the item - * @return the slotheigt of the specific item - */ - protected abstract int getSlotHeight(int index); - - /** - * Return the height of the content being scrolled - */ - protected int getContentHeight() - { - int slotHeight = this.headerPadding; - for (int index = 0; index < this.getSize(); ++index) - { - slotHeight += this.getSlotHeight(index); - } - - return slotHeight; - } - - protected abstract void drawBackground(); - - protected void slotOutOfBounds(int index, int p_178040_2_, int p_178040_3_) {} - - protected abstract void drawSlot(int entryID, int x, int y, int h, int mouseXIn, int mouseYIn); - - /** - * Handles drawing a list's header row. - */ - protected void drawListHeader(int x, int y, Tessellator tess) {} - - protected void func_148132_a(int p_148132_1_, int p_148132_2_) {} - - protected void func_148142_b(int p_148142_1_, int p_148142_2_) {} - - public int getSlotIndexFromScreenCoords(int x, int y) - { - int k = this.left + (this.width / 2 - this.getListWidth() / 2); - int l = this.left + (this.width / 2 + this.getListWidth() / 2) - this.scrollBarWidth; - int i1 = y - this.top - this.headerPadding + (int)this.amountScrolled; - - int yStart = 0; - int yStop = yStart + this.getSlotHeight(0); - - for (int index = 0; index < this.getSize(); ++index) - { - if (i1 >= yStart && i1 <= yStop) - { - return x < this.getScrollBarX() && x >= k && x <= l && i1 >= 0 ? index : -1; - } - yStart = yStop; - yStop += this.getSlotHeight(index + 1); - } - return -1; - } - - /** - * Registers the IDs that can be used for the scrollbar's up/down buttons. - */ - public void registerScrollButtons(int scrollUpButtonIDIn, int scrollDownButtonIDIn) - { - this.scrollUpButtonID = scrollUpButtonIDIn; - this.scrollDownButtonID = scrollDownButtonIDIn; - } - - /** - * Stop the thing from scrolling out of bounds - */ - protected void bindAmountScrolled() - { - int i = this.func_148135_f(); - - if (i < 0) - { - i /= 2; - } - - if (!this.field_148163_i && i < 0) - { - i = 0; - } - - this.amountScrolled = MathHelper.clamp_float(this.amountScrolled, 0.0F, (float)i); - } - - public int func_148135_f() - { - return Math.max(0, this.getContentHeight() - (this.bottom - this.top)); - } - - /** - * Returns the amountScrolled field as an integer. - */ - public int getAmountScrolled() - { - return (int)this.amountScrolled; - } - - public boolean isMouseYWithinSlotBounds() - { - return this.mouseY >= this.top && this.mouseY <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; - } - - public boolean isMouseXWithinSlotBounds() - { - return this.mouseX >= this.left && this.mouseX <= this.right; - } - - public boolean isMouseInField() - { - return this.isMouseYWithinSlotBounds() && this.isMouseXWithinSlotBounds(); - } - - /** - * Scrolls the slot by the given amount. A positive value scrolls down, and a negative value scrolls up. - */ - public void scrollBy(int amount) - { - this.amountScrolled += (float)amount; - this.bindAmountScrolled(); - this.initialClickY = -2.0F; - } - - public void actionPerformed(GuiButton button) - { - if (button.enabled) - { - int slotHeight = this.getAverageSlotHeight(); - if (button.id == this.scrollUpButtonID) - { - this.amountScrolled -= (float)(slotHeight * 2 / 3); - this.initialClickY = -2.0F; - this.bindAmountScrolled(); - } - else if (button.id == this.scrollDownButtonID) - { - this.amountScrolled += (float)(slotHeight * 2 / 3); - this.initialClickY = -2.0F; - this.bindAmountScrolled(); - } - } - } - - public void drawScreen(int mouseXIn, int mouseYIn, float f) - { - if (this.getEnabled()) - { - this.mouseX = mouseXIn; - this.mouseY = mouseYIn; - this.drawBackground(); - int k = this.getScrollBarX(); - int l = k + this.scrollBarWidth; - this.bindAmountScrolled(); - GlStateManager.disableLighting(); - GlStateManager.disableFog(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.drawContainerBackground(tessellator); - int i1 = this.left + (this.width / 2 - this.getListWidth() / 2); - int j1 = this.top - (int)this.amountScrolled; - - if (this.hasListHeader) - { - this.drawListHeader(i1, j1, tessellator); - } - - this.drawSelectionBox(i1, j1, mouseXIn, mouseYIn); - GlStateManager.disableDepth(); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1); - GlStateManager.disableAlpha(); - GlStateManager.shadeModel(7425); - GlStateManager.disableTexture2D(); - - int k1 = this.func_148135_f(); - - if (k1 > 0) - { - int l1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); - l1 = MathHelper.clamp_int(l1, 32, this.bottom - this.top - 8); - int i2 = (int)this.amountScrolled * (this.bottom - this.top - l1) / k1 + this.top; - - if (i2 < this.top) - { - i2 = this.top; - } - //draw the scrollbar - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(0, 255); - worldrenderer.addVertexWithUV((double)k, (double)this.bottom, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)l, (double)this.bottom, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)l, (double)this.top, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)k, (double)this.top, 0.0D, 0.0D, 0.0D); - tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(8421504, 255); - worldrenderer.addVertexWithUV((double)k, (double)(i2 + l1), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)l, (double)(i2 + l1), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)l, (double)i2, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)k, (double)i2, 0.0D, 0.0D, 0.0D); - tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(12632256, 255); - worldrenderer.addVertexWithUV((double)k, (double)(i2 + l1 - 1), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(l - 1), (double)(i2 + l1 - 1), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(l - 1), (double)i2, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)k, (double)i2, 0.0D, 0.0D, 0.0D); - tessellator.draw(); - } - - this.func_148142_b(mouseXIn, mouseYIn); - GlStateManager.enableTexture2D(); - GlStateManager.shadeModel(7424); - GlStateManager.enableAlpha(); - GlStateManager.disableBlend(); - } - } - - public void handleMouseInput() - { - if (this.isMouseInField()) - { - if (Mouse.isButtonDown(0) && this.getEnabled()) - { - if (this.initialClickY == -1.0F) - { - boolean flag = true; - - if (this.mouseY >= this.top && this.mouseY <= this.bottom) - { - int i = (this.width / 2 - this.getListWidth() / 2) + this.left; - int j = (this.width / 2 + this.getListWidth() / 2) + this.left - this.scrollBarWidth; - int k = this.mouseY - this.top - this.headerPadding + (int)this.amountScrolled; - int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); - - if (this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) - { - boolean flag1 = l == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; - this.elementClicked(l, flag1, this.mouseX, this.mouseY, 0); - this.selectedElement = l; - this.lastClicked = Minecraft.getSystemTime(); - } - else if (this.mouseX >= i && this.mouseX <= j && k < 0) - { - this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int)this.amountScrolled); - flag = false; - } - - int i2 = this.getScrollBarX(); - int i1 = i2 + this.scrollBarWidth; - - if (this.mouseX >= i2 && this.mouseX <= i1) - { - this.scrollMultiplier = -1.0F; - int j1 = this.func_148135_f(); - - if (j1 < 1) - { - j1 = 1; - } - - int k1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); - k1 = MathHelper.clamp_int(k1, 32, this.bottom - this.top - 8); - this.scrollMultiplier /= (float)(this.bottom - this.top - k1) / (float)j1; - } - else - { - this.scrollMultiplier = 1.0F; - } - - if (flag) - { - this.initialClickY = (float)this.mouseY; - } - else - { - this.initialClickY = -2.0F; - } - } - else - { - this.initialClickY = -2.0F; - } - } - else if (this.initialClickY >= 0.0F) - { - this.amountScrolled -= ((float)this.mouseY - this.initialClickY) * this.scrollMultiplier; - this.initialClickY = (float)this.mouseY; - } - } - else - { - this.initialClickY = -1.0F; - } - - if (Mouse.isButtonDown(1) && this.getEnabled()) - { - if (this.initialClickY == -1.0F) - { - boolean flag = true; - - if (this.mouseY >= this.top && this.mouseY <= this.bottom) - { - int i = (this.width / 2 - this.getListWidth() / 2) + this.left; - int j = (this.width / 2 + this.getListWidth() / 2) + this.left - this.scrollBarWidth; - int k = this.mouseY - this.top - this.headerPadding + (int)this.amountScrolled; - int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); - - if (this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) - { - boolean flag1 = l == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; - this.elementClicked(l, flag1, this.mouseX, this.mouseY, 1); - this.selectedElement = l; - this.lastClicked = Minecraft.getSystemTime(); - } - else if (this.mouseX >= i && this.mouseX <= j && k < 0) - { - this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int)this.amountScrolled); - flag = false; - } - } - } - } - - int l1 = Mouse.getEventDWheel(); - - if (l1 != 0) - { - if (l1 > 0) - { - l1 = -1; - } - else if (l1 < 0) - { - l1 = 1; - } - - this.amountScrolled += (float)(l1 * this.getAverageSlotHeight() / 2); - } - } - } - - public void setEnabled(boolean enabledIn) - { - this.enabled = enabledIn; - } - - public boolean getEnabled() - { - return this.enabled; - } - - /** - * Gets the width of the list - */ - public int getListWidth() - { - return this.width; - } - - /** - * Draws the selection box around the selected slot element. - */ - protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) - { - int i1 = this.getSize(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - - int yTotal = y + this.headerPadding; - - for (int index = 0; index < i1; ++index) - { - int slotHeight = getSlotHeight(index); - - if (yTotal + slotHeight > this.bottom || yTotal < this.top) - { - this.slotOutOfBounds(index, x, yTotal); - yTotal += slotHeight; - continue; - } - - if (this.showSelectionBox && this.isSelected(index)) - { - int xLeft = this.left + (this.width / 2 - this.getListWidth() / 2); - int xRight = this.left + (this.width / 2 + this.getListWidth() / 2) - this.scrollBarWidth; - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableTexture2D(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorOpaque_I(8421504); - worldrenderer.addVertexWithUV((double)xLeft, (double)(yTotal + slotHeight), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)xRight, (double)(yTotal + slotHeight), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)xRight, (double)(yTotal), 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)xLeft, (double)(yTotal), 0.0D, 0.0D, 0.0D); - worldrenderer.setColorOpaque_I(0); - worldrenderer.addVertexWithUV((double)(xLeft + 1), (double)(yTotal + slotHeight - 1), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(xRight - 1), (double)(yTotal + slotHeight - 1), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(xRight - 1), (double)(yTotal + 1), 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)(xLeft + 1), (double)(yTotal + 1), 0.0D, 0.0D, 0.0D); - tessellator.draw(); - GlStateManager.enableTexture2D(); - } - - this.drawSlot(index, x + 4, yTotal + this.spacingY, slotHeight, mouseXIn, mouseYIn); - - yTotal += slotHeight; - } - } - - protected int getScrollBarX() - { - return left + this.width - this.scrollBarWidth; - } - - /** - * Sets the left and right bounds of the slot. Param is the left bound, right is calculated as left + width. - */ - public void setSlotXBoundsFromLeft(int leftIn) - { - this.left = leftIn; - this.right = leftIn + this.width; - } - - public int getAverageSlotHeight() - { - int height = 0; - int biggest = 0; - for (int index = 0; index < this.getSize(); ++index) - { - int slotheight = this.getSlotHeight(index); - height += slotheight; - - biggest = biggest < slotheight ? slotheight : biggest; - } - - return height > 0 ? height / this.getSize() : 9; - } - - protected void drawContainerBackground(Tessellator tessellator) - { - Gui.drawRect(left, top, right, bottom, 0x80000000); - } + + public MwGuiSlot(Minecraft mcIn, int width, int height, int topIn, int bottomIn, int left) + { + this.mc = mcIn; + this.width = width; + this.height = height; + this.top = topIn; + this.bottom = bottomIn; + this.left = left; + this.right = left + width; + } + + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn, int left) + { + this.width = widthIn; + this.height = heightIn; + this.top = topIn; + this.bottom = bottomIn; + this.left = left; + this.right = left + widthIn; + } + + public void setShowSelectionBox(boolean showSelectionBoxIn) + { + this.showSelectionBox = showSelectionBoxIn; + } + + /** + * Sets hasListHeader and headerHeight. Params: hasListHeader, headerHeight. + * If hasListHeader is false headerHeight is set to 0. + */ + protected void setHasListHeader(boolean hasListHeaderIn, int headerPaddingIn) + { + this.hasListHeader = hasListHeaderIn; + this.headerPadding = headerPaddingIn; + + if (!hasListHeaderIn) + { + this.headerPadding = 0; + } + } + + protected abstract int getSize(); + + /** + * The element in the slot that was clicked, boolean for whether it was + * double clicked or not + */ + protected abstract void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY, int mouseButton); + + /** + * Returns true if the element passed in is currently selected + */ + protected abstract boolean isSelected(int slotIndex); + + /** + * + * @param index + * of the item + * @return the slotheigt of the specific item + */ + protected abstract int getSlotHeight(int index); + + /** + * Return the height of the content being scrolled + */ + protected int getContentHeight() + { + int slotHeight = this.headerPadding; + for (int index = 0; index < this.getSize(); ++index) + { + slotHeight += this.getSlotHeight(index); + } + + return slotHeight; + } + + protected abstract void drawBackground(); + + protected void slotOutOfBounds(int index, int p_178040_2_, int p_178040_3_) + { + } + + protected abstract void drawSlot(int entryID, int x, int y, int h, int mouseXIn, int mouseYIn); + + /** + * Handles drawing a list's header row. + */ + protected void drawListHeader(int x, int y, Tessellator tess) + { + } + + protected void func_148132_a(int p_148132_1_, int p_148132_2_) + { + } + + protected void func_148142_b(int p_148142_1_, int p_148142_2_) + { + } + + public int getSlotIndexFromScreenCoords(int x, int y) + { + int k = this.left + ((this.width / 2) - (this.getListWidth() / 2)); + int l = (this.left + ((this.width / 2) + (this.getListWidth() / 2))) - this.scrollBarWidth; + int i1 = (y - this.top - this.headerPadding) + (int) this.amountScrolled; + + int yStart = 0; + int yStop = yStart + this.getSlotHeight(0); + + for (int index = 0; index < this.getSize(); ++index) + { + if ((i1 >= yStart) && (i1 <= yStop)) + { + return (x < this.getScrollBarX()) && (x >= k) && (x <= l) && (i1 >= 0) ? index : -1; + } + yStart = yStop; + yStop += this.getSlotHeight(index + 1); + } + return -1; + } + + /** + * Registers the IDs that can be used for the scrollbar's up/down buttons. + */ + public void registerScrollButtons(int scrollUpButtonIDIn, int scrollDownButtonIDIn) + { + this.scrollUpButtonID = scrollUpButtonIDIn; + this.scrollDownButtonID = scrollDownButtonIDIn; + } + + /** + * Stop the thing from scrolling out of bounds + */ + protected void bindAmountScrolled() + { + int i = this.func_148135_f(); + + if (i < 0) + { + i /= 2; + } + + if (!this.field_148163_i && (i < 0)) + { + i = 0; + } + + this.amountScrolled = MathHelper.clamp_float(this.amountScrolled, 0.0F, i); + } + + public int func_148135_f() + { + return Math.max(0, this.getContentHeight() - (this.bottom - this.top)); + } + + /** + * Returns the amountScrolled field as an integer. + */ + public int getAmountScrolled() + { + return (int) this.amountScrolled; + } + + public boolean isMouseYWithinSlotBounds() + { + return (this.mouseY >= this.top) && (this.mouseY <= this.bottom) && (this.mouseX >= this.left) && (this.mouseX <= this.right); + } + + public boolean isMouseXWithinSlotBounds() + { + return (this.mouseX >= this.left) && (this.mouseX <= this.right); + } + + public boolean isMouseInField() + { + return this.isMouseYWithinSlotBounds() && this.isMouseXWithinSlotBounds(); + } + + /** + * Scrolls the slot by the given amount. A positive value scrolls down, and + * a negative value scrolls up. + */ + public void scrollBy(int amount) + { + this.amountScrolled += amount; + this.bindAmountScrolled(); + this.initialClickY = -2.0F; + } + + public void actionPerformed(GuiButton button) + { + if (button.enabled) + { + int slotHeight = this.getAverageSlotHeight(); + if (button.id == this.scrollUpButtonID) + { + this.amountScrolled -= (slotHeight * 2) / 3; + this.initialClickY = -2.0F; + this.bindAmountScrolled(); + } + else if (button.id == this.scrollDownButtonID) + { + this.amountScrolled += (slotHeight * 2) / 3; + this.initialClickY = -2.0F; + this.bindAmountScrolled(); + } + } + } + + public void drawScreen(int mouseXIn, int mouseYIn, float f) + { + if (this.getEnabled()) + { + this.mouseX = mouseXIn; + this.mouseY = mouseYIn; + this.drawBackground(); + int k = this.getScrollBarX(); + int l = k + this.scrollBarWidth; + this.bindAmountScrolled(); + GlStateManager.disableLighting(); + GlStateManager.disableFog(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.drawContainerBackground(tessellator); + int i1 = this.left + ((this.width / 2) - (this.getListWidth() / 2)); + int j1 = this.top - (int) this.amountScrolled; + + if (this.hasListHeader) + { + this.drawListHeader(i1, j1, tessellator); + } + + this.drawSelectionBox(i1, j1, mouseXIn, mouseYIn); + GlStateManager.disableDepth(); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1); + GlStateManager.disableAlpha(); + GlStateManager.shadeModel(7425); + GlStateManager.disableTexture2D(); + + int k1 = this.func_148135_f(); + + if (k1 > 0) + { + int l1 = ((this.bottom - this.top) * (this.bottom - this.top)) / this.getContentHeight(); + l1 = MathHelper.clamp_int(l1, 32, this.bottom - this.top - 8); + int i2 = (((int) this.amountScrolled * (this.bottom - this.top - l1)) / k1) + this.top; + + if (i2 < this.top) + { + i2 = this.top; + } + // draw the scrollbar + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(0, 255); + worldrenderer.addVertexWithUV(k, this.bottom, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV(l, this.bottom, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV(l, this.top, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV(k, this.top, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(8421504, 255); + worldrenderer.addVertexWithUV(k, i2 + l1, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV(l, i2 + l1, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV(l, i2, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV(k, i2, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorRGBA_I(12632256, 255); + worldrenderer.addVertexWithUV(k, (i2 + l1) - 1, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV(l - 1, (i2 + l1) - 1, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV(l - 1, i2, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV(k, i2, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + } + + this.func_148142_b(mouseXIn, mouseYIn); + GlStateManager.enableTexture2D(); + GlStateManager.shadeModel(7424); + GlStateManager.enableAlpha(); + GlStateManager.disableBlend(); + } + } + + public void handleMouseInput() + { + if (this.isMouseInField()) + { + if (Mouse.isButtonDown(0) && this.getEnabled()) + { + if (this.initialClickY == -1.0F) + { + boolean flag = true; + + if ((this.mouseY >= this.top) && (this.mouseY <= this.bottom)) + { + int i = ((this.width / 2) - (this.getListWidth() / 2)) + this.left; + int j = (((this.width / 2) + (this.getListWidth() / 2)) + this.left) - this.scrollBarWidth; + int k = (this.mouseY - this.top - this.headerPadding) + (int) this.amountScrolled; + int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); + + if ((this.mouseX >= i) && (this.mouseX <= j) && (l >= 0) && (k >= 0) && (l < this.getSize())) + { + boolean flag1 = (l == this.selectedElement) && ((Minecraft.getSystemTime() - this.lastClicked) < 250L); + this.elementClicked(l, flag1, this.mouseX, this.mouseY, 0); + this.selectedElement = l; + this.lastClicked = Minecraft.getSystemTime(); + } + else if ((this.mouseX >= i) && (this.mouseX <= j) && (k < 0)) + { + this.func_148132_a(this.mouseX - i, (this.mouseY - this.top) + (int) this.amountScrolled); + flag = false; + } + + int i2 = this.getScrollBarX(); + int i1 = i2 + this.scrollBarWidth; + + if ((this.mouseX >= i2) && (this.mouseX <= i1)) + { + this.scrollMultiplier = -1.0F; + int j1 = this.func_148135_f(); + + if (j1 < 1) + { + j1 = 1; + } + + int k1 = (int) ((float) ((this.bottom - this.top) * (this.bottom - this.top)) / (float) this.getContentHeight()); + k1 = MathHelper.clamp_int(k1, 32, this.bottom - this.top - 8); + this.scrollMultiplier /= (float) (this.bottom - this.top - k1) / (float) j1; + } + else + { + this.scrollMultiplier = 1.0F; + } + + if (flag) + { + this.initialClickY = this.mouseY; + } + else + { + this.initialClickY = -2.0F; + } + } + else + { + this.initialClickY = -2.0F; + } + } + else if (this.initialClickY >= 0.0F) + { + this.amountScrolled -= (this.mouseY - this.initialClickY) * this.scrollMultiplier; + this.initialClickY = this.mouseY; + } + } + else + { + this.initialClickY = -1.0F; + } + + if (Mouse.isButtonDown(1) && this.getEnabled()) + { + if (this.initialClickY == -1.0F) + { + if ((this.mouseY >= this.top) && (this.mouseY <= this.bottom)) + { + int i = ((this.width / 2) - (this.getListWidth() / 2)) + this.left; + int j = (((this.width / 2) + (this.getListWidth() / 2)) + this.left) - this.scrollBarWidth; + int k = (this.mouseY - this.top - this.headerPadding) + (int) this.amountScrolled; + int l = this.getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); + + if ((this.mouseX >= i) && (this.mouseX <= j) && (l >= 0) && (k >= 0) && (l < this.getSize())) + { + boolean flag1 = (l == this.selectedElement) && ((Minecraft.getSystemTime() - this.lastClicked) < 250L); + this.elementClicked(l, flag1, this.mouseX, this.mouseY, 1); + this.selectedElement = l; + this.lastClicked = Minecraft.getSystemTime(); + } + else if ((this.mouseX >= i) && (this.mouseX <= j) && (k < 0)) + { + this.func_148132_a(this.mouseX - i, (this.mouseY - this.top) + (int) this.amountScrolled); + } + } + } + } + + int l1 = Mouse.getEventDWheel(); + + if (l1 != 0) + { + if (l1 > 0) + { + l1 = -1; + } + else if (l1 < 0) + { + l1 = 1; + } + + this.amountScrolled += (l1 * this.getAverageSlotHeight()) / 2; + } + } + } + + public void setEnabled(boolean enabledIn) + { + this.enabled = enabledIn; + } + + public boolean getEnabled() + { + return this.enabled; + } + + /** + * Gets the width of the list + */ + public int getListWidth() + { + return this.width; + } + + /** + * Draws the selection box around the selected slot element. + */ + protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) + { + int i1 = this.getSize(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + int yTotal = y + this.headerPadding; + + for (int index = 0; index < i1; ++index) + { + int slotHeight = this.getSlotHeight(index); + + if (((yTotal + slotHeight) > this.bottom) || (yTotal < this.top)) + { + this.slotOutOfBounds(index, x, yTotal); + yTotal += slotHeight; + continue; + } + + if (this.showSelectionBox && this.isSelected(index)) + { + int xLeft = this.left + ((this.width / 2) - (this.getListWidth() / 2)); + int xRight = (this.left + ((this.width / 2) + (this.getListWidth() / 2))) - this.scrollBarWidth; + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableTexture2D(); + worldrenderer.startDrawingQuads(); + worldrenderer.setColorOpaque_I(8421504); + worldrenderer.addVertexWithUV(xLeft, yTotal + slotHeight, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV(xRight, yTotal + slotHeight, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV(xRight, (yTotal), 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV(xLeft, (yTotal), 0.0D, 0.0D, 0.0D); + worldrenderer.setColorOpaque_I(0); + worldrenderer.addVertexWithUV(xLeft + 1, (yTotal + slotHeight) - 1, 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV(xRight - 1, (yTotal + slotHeight) - 1, 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV(xRight - 1, yTotal + 1, 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV(xLeft + 1, yTotal + 1, 0.0D, 0.0D, 0.0D); + tessellator.draw(); + GlStateManager.enableTexture2D(); + } + + this.drawSlot(index, x + 4, yTotal + this.spacingY, slotHeight, mouseXIn, mouseYIn); + + yTotal += slotHeight; + } + } + + protected int getScrollBarX() + { + return (this.left + this.width) - this.scrollBarWidth; + } + + /** + * Sets the left and right bounds of the slot. Param is the left bound, + * right is calculated as left + width. + */ + public void setSlotXBoundsFromLeft(int leftIn) + { + this.left = leftIn; + this.right = leftIn + this.width; + } + + public int getAverageSlotHeight() + { + int height = 0; + int biggest = 0; + for (int index = 0; index < this.getSize(); ++index) + { + int slotheight = this.getSlotHeight(index); + height += slotheight; + + biggest = biggest < slotheight ? slotheight : biggest; + } + + return height > 0 ? height / this.getSize() : 9; + } + + protected void drawContainerBackground(Tessellator tessellator) + { + Gui.drawRect(this.left, this.top, this.right, this.bottom, 0x80000000); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index 1ad8fe1e..43bb5d78 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -1,42 +1,43 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import mapwriter.config.Config; -import mapwriter.map.MapView; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiTeleportDialog extends MwGuiTextDialog { - - final Mw mw; - final MapView mapView; - final int teleportX, teleportZ; - - public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) { - super(parentScreen, - I18n.format("mw.gui.mwguimarkerdialognew.title", new Object[0]) + ":", - Integer.toString(y), - I18n.format("mw.gui.mwguimarkerdialognew.error", new Object[0])); - this.mw = mw; - this.mapView = mapView; - this.teleportX = x; - this.teleportZ = z; - this.backToGameOnSubmit = true; - } - - @Override - public boolean submit() { - boolean done = false; - int height = this.getInputAsInt(); - if (this.inputValid) { - height = Math.min(Math.max(0, height), 255); - Config.defaultTeleportHeight = height; - this.mw.teleportToMapPos(this.mapView, this.teleportX, height, this.teleportZ); - done = true; - } - return done; - } -} +package mapwriter.gui; + +import mapwriter.Mw; +import mapwriter.config.Config; +import mapwriter.map.MapView; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiTeleportDialog extends MwGuiTextDialog +{ + + final Mw mw; + final MapView mapView; + final int teleportX, teleportZ; + + public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) + { + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialognew.title", new Object[0]) + ":", Integer.toString(y), I18n.format("mw.gui.mwguimarkerdialognew.error", new Object[0])); + this.mw = mw; + this.mapView = mapView; + this.teleportX = x; + this.teleportZ = z; + this.backToGameOnSubmit = true; + } + + @Override + public boolean submit() + { + boolean done = false; + int height = this.getInputAsInt(); + if (this.inputValid) + { + height = Math.min(Math.max(0, height), 255); + Config.defaultTeleportHeight = height; + this.mw.teleportToMapPos(this.mapView, this.teleportX, height, this.teleportZ); + done = true; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiTextDialog.java b/src/main/java/mapwriter/gui/MwGuiTextDialog.java index a4788552..9bf956a2 100644 --- a/src/main/java/mapwriter/gui/MwGuiTextDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTextDialog.java @@ -1,160 +1,173 @@ -package mapwriter.gui; - -import java.io.IOException; - -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; - -import org.lwjgl.input.Keyboard; - -public class MwGuiTextDialog extends GuiScreen { - - private final GuiScreen parentScreen; - - String title; - String text; - String error; - GuiTextField textField = null; - boolean inputValid = false; - boolean showError = false; - boolean backToGameOnSubmit = false; - static final int textDialogWidthPercent = 50; - static final int textDialogTitleY = 80; - static final int textDialogY = 92; - static final int textDialogErrorY = 108; - - public MwGuiTextDialog(GuiScreen parentScreen, String title, String text, String error) { - this.parentScreen = parentScreen; - this.title = title; - this.text = text; - this.error = error; - } - - private void newTextField() { - if (this.textField != null) { - this.text = this.textField.getText(); - } - int w = this.width * textDialogWidthPercent / 100; - this.textField = new GuiTextField(0,this.fontRendererObj, - (this.width - w) / 2 + 5, - textDialogY, - w - 10, - 12); - this.textField.setMaxStringLength(32); - this.textField.setFocused(true); - this.textField.setCanLoseFocus(false); - //this.textField.setEnableBackgroundDrawing(false); - this.textField.setText(this.text); - } - - public void setText(String s) { - this.textField.setText(s); - this.text = s; - } - - public String getInputAsString() { - String s = this.textField.getText().trim(); - this.inputValid = (s.length() > 0); - this.showError = !this.inputValid; - return s; - } - - public int getInputAsInt() { - String s = this.getInputAsString(); - int value = 0; - try { - value = Integer.parseInt(s); - this.inputValid = true; - this.showError = false; - } catch (NumberFormatException e) { - this.inputValid = false; - this.showError = true; - } - return value; - } - - public int getInputAsHexInt() { - String s = this.getInputAsString(); - int value = 0; - try { - value = Integer.parseInt(s, 16); - this.inputValid = true; - this.showError = false; - } catch (NumberFormatException e) { - this.inputValid = false; - this.showError = true; - } - return value; - } - - public boolean submit() { - return false; - } - - public void initGui() { - this.newTextField(); - } - - public void drawScreen(int mouseX, int mouseY, float f) { - - if (this.parentScreen != null) { - this.parentScreen.drawScreen(mouseX, mouseY, f); - } else { - this.drawDefaultBackground(); - } - - int w = this.width * textDialogWidthPercent / 100; - drawRect( - (this.width - w) / 2, - textDialogTitleY - 4, - (this.width - w) / 2 + w, - textDialogErrorY + 14, - 0x80000000); - this.drawCenteredString( - this.fontRendererObj, - this.title, - this.width / 2, - textDialogTitleY, - 0xffffff); - this.textField.drawTextBox(); - if (this.showError) { - this.drawCenteredString( - this.fontRendererObj, - this.error, - this.width / 2, - textDialogErrorY, - 0xffffff); - } - - super.drawScreen(mouseX, mouseY, f); - } - - protected void mouseClicked(int x, int y, int button) throws IOException { - super.mouseClicked(x, y, button); - } - - protected void keyTyped(char c, int key) { - switch (key) { - case Keyboard.KEY_ESCAPE: - this.mc.displayGuiScreen(this.parentScreen); - break; - - case Keyboard.KEY_RETURN: - // when enter pressed, submit current input - if (this.submit()) { - if (!this.backToGameOnSubmit) { - this.mc.displayGuiScreen(this.parentScreen); - } else { - this.mc.displayGuiScreen(null); - } - } - break; - - default: - // other characters are processed by the text box - this.textField.textboxKeyTyped(c, key); - this.text = this.textField.getText(); - break; - } - } -} +package mapwriter.gui; + +import java.io.IOException; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; + +import org.lwjgl.input.Keyboard; + +public class MwGuiTextDialog extends GuiScreen +{ + + private final GuiScreen parentScreen; + + String title; + String text; + String error; + GuiTextField textField = null; + boolean inputValid = false; + boolean showError = false; + boolean backToGameOnSubmit = false; + static final int textDialogWidthPercent = 50; + static final int textDialogTitleY = 80; + static final int textDialogY = 92; + static final int textDialogErrorY = 108; + + public MwGuiTextDialog(GuiScreen parentScreen, String title, String text, String error) + { + this.parentScreen = parentScreen; + this.title = title; + this.text = text; + this.error = error; + } + + private void newTextField() + { + if (this.textField != null) + { + this.text = this.textField.getText(); + } + int w = (this.width * textDialogWidthPercent) / 100; + this.textField = new GuiTextField(0, this.fontRendererObj, ((this.width - w) / 2) + 5, textDialogY, w - 10, 12); + this.textField.setMaxStringLength(32); + this.textField.setFocused(true); + this.textField.setCanLoseFocus(false); + // this.textField.setEnableBackgroundDrawing(false); + this.textField.setText(this.text); + } + + public void setText(String s) + { + this.textField.setText(s); + this.text = s; + } + + public String getInputAsString() + { + String s = this.textField.getText().trim(); + this.inputValid = (s.length() > 0); + this.showError = !this.inputValid; + return s; + } + + public int getInputAsInt() + { + String s = this.getInputAsString(); + int value = 0; + try + { + value = Integer.parseInt(s); + this.inputValid = true; + this.showError = false; + } + catch (NumberFormatException e) + { + this.inputValid = false; + this.showError = true; + } + return value; + } + + public int getInputAsHexInt() + { + String s = this.getInputAsString(); + int value = 0; + try + { + value = Integer.parseInt(s, 16); + this.inputValid = true; + this.showError = false; + } + catch (NumberFormatException e) + { + this.inputValid = false; + this.showError = true; + } + return value; + } + + public boolean submit() + { + return false; + } + + @Override + public void initGui() + { + this.newTextField(); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) + { + + if (this.parentScreen != null) + { + this.parentScreen.drawScreen(mouseX, mouseY, f); + } + else + { + this.drawDefaultBackground(); + } + + int w = (this.width * textDialogWidthPercent) / 100; + drawRect((this.width - w) / 2, textDialogTitleY - 4, ((this.width - w) / 2) + w, textDialogErrorY + 14, 0x80000000); + this.drawCenteredString(this.fontRendererObj, this.title, this.width / 2, textDialogTitleY, 0xffffff); + this.textField.drawTextBox(); + if (this.showError) + { + this.drawCenteredString(this.fontRendererObj, this.error, this.width / 2, textDialogErrorY, 0xffffff); + } + + super.drawScreen(mouseX, mouseY, f); + } + + @Override + protected void mouseClicked(int x, int y, int button) throws IOException + { + super.mouseClicked(x, y, button); + } + + @Override + protected void keyTyped(char c, int key) + { + switch (key) + { + case Keyboard.KEY_ESCAPE: + this.mc.displayGuiScreen(this.parentScreen); + break; + + case Keyboard.KEY_RETURN: + // when enter pressed, submit current input + if (this.submit()) + { + if (!this.backToGameOnSubmit) + { + this.mc.displayGuiScreen(this.parentScreen); + } + else + { + this.mc.displayGuiScreen(null); + } + } + break; + + default: + // other characters are processed by the text box + this.textField.textboxKeyTyped(c, key); + this.text = this.textField.getText(); + break; + } + } +} diff --git a/src/main/java/mapwriter/gui/ScrollableColorSelector.java b/src/main/java/mapwriter/gui/ScrollableColorSelector.java index 5828f140..5d9591f2 100644 --- a/src/main/java/mapwriter/gui/ScrollableColorSelector.java +++ b/src/main/java/mapwriter/gui/ScrollableColorSelector.java @@ -1,12 +1,8 @@ package mapwriter.gui; -import java.util.List; - -import org.lwjgl.input.Keyboard; - import mapwriter.util.Utils; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.gui.Gui; import net.minecraft.client.resources.I18n; public class ScrollableColorSelector extends ScrollableField @@ -14,142 +10,102 @@ public class ScrollableColorSelector extends ScrollableField private String editRed = "mw.gui.ScrollableColorSelector.Red"; private String editGreen = "mw.gui.ScrollableColorSelector.Green"; private String editBlue = "mw.gui.ScrollableColorSelector.Blue"; - + private ScrollableNumericTextBox ScrollableNumericTextBoxColourRed; private ScrollableNumericTextBox ScrollableNumericTextBoxColourGreen; private ScrollableNumericTextBox ScrollableNumericTextBoxColourBlue; - - private int colour = 0; - + + private int colour = 0; + private int colourFieldX = 0; private int colourFieldY = 0; private int colourFieldW = 0; private int colourFieldH = 0; - + private int y; - - public ScrollableColorSelector( - int x, - int y, - int width, - String label, - FontRenderer fontrendererObj - ) + + public ScrollableColorSelector(int x, int y, int width, String label, FontRenderer fontrendererObj) { super(x, y + MwGuiMarkerDialogNew.elementVSpacing, width, label, fontrendererObj); this.y = y; this.init(); } - - private void init() + + private void init() { int textboxWidth = 16; int x1 = this.x + ScrollableField.arrowsWidth + this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) + 4; - int w = (ScrollableField.arrowsWidth * 2) + - this.fontrendererObj.getStringWidth("999") - + textboxWidth; - - ScrollableNumericTextBoxColourRed = new ScrollableNumericTextBox( - x1, - this.y, - w, - I18n.format(this.editRed, new Object[0]), - this.fontrendererObj - ); - ScrollableNumericTextBoxColourRed.setDrawArrows(true); - ScrollableNumericTextBoxColourRed.setMaxValue(255); - ScrollableNumericTextBoxColourRed.setMinValue(0); - - ScrollableNumericTextBoxColourGreen = new ScrollableNumericTextBox( - x1, - this.y + MwGuiMarkerDialogNew.elementVSpacing, - w, - I18n.format(this.editGreen, new Object[0]), - this.fontrendererObj - ); - ScrollableNumericTextBoxColourGreen.setDrawArrows(true); - ScrollableNumericTextBoxColourGreen.setMaxValue(255); - ScrollableNumericTextBoxColourGreen.setMinValue(0); - - ScrollableNumericTextBoxColourBlue = new ScrollableNumericTextBox( - x1, - this.y + MwGuiMarkerDialogNew.elementVSpacing * 2, - w, - I18n.format(this.editBlue, new Object[0]), - this.fontrendererObj - ); - ScrollableNumericTextBoxColourBlue.setDrawArrows(true); - ScrollableNumericTextBoxColourBlue.setMaxValue(255); - ScrollableNumericTextBoxColourBlue.setMinValue(0); - - colourFieldX = x1 + w + 2; - colourFieldY = this.y + 6; - colourFieldW = this.width - - w - - (ScrollableField.arrowsWidth * 2) - - this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) - - 8; - colourFieldH = MwGuiMarkerDialogNew.elementVSpacing * 2; + int w = (ScrollableField.arrowsWidth * 2) + this.fontrendererObj.getStringWidth("999") + textboxWidth; + + this.ScrollableNumericTextBoxColourRed = new ScrollableNumericTextBox(x1, this.y, w, I18n.format(this.editRed, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourRed.setDrawArrows(true); + this.ScrollableNumericTextBoxColourRed.setMaxValue(255); + this.ScrollableNumericTextBoxColourRed.setMinValue(0); + + this.ScrollableNumericTextBoxColourGreen = new ScrollableNumericTextBox(x1, this.y + MwGuiMarkerDialogNew.elementVSpacing, w, I18n.format(this.editGreen, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourGreen.setDrawArrows(true); + this.ScrollableNumericTextBoxColourGreen.setMaxValue(255); + this.ScrollableNumericTextBoxColourGreen.setMinValue(0); + + this.ScrollableNumericTextBoxColourBlue = new ScrollableNumericTextBox(x1, this.y + (MwGuiMarkerDialogNew.elementVSpacing * 2), w, I18n.format(this.editBlue, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourBlue.setDrawArrows(true); + this.ScrollableNumericTextBoxColourBlue.setMaxValue(255); + this.ScrollableNumericTextBoxColourBlue.setMinValue(0); + + this.colourFieldX = x1 + w + 2; + this.colourFieldY = this.y + 6; + this.colourFieldW = this.width - w - (ScrollableField.arrowsWidth * 2) - this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) - 8; + this.colourFieldH = MwGuiMarkerDialogNew.elementVSpacing * 2; } @Override - public void nextElement() + public void nextElement() { - setColor(Utils.getNextColour()); + this.setColor(Utils.getNextColour()); } @Override - public void previousElement() + public void previousElement() { - setColor(Utils.getPrevColour()); + this.setColor(Utils.getPrevColour()); } @Override - public void setFocused(Boolean focus) + public void setFocused(Boolean focus) { this.ScrollableNumericTextBoxColourRed.setFocused(focus); } @Override - public Boolean isFocused() + public Boolean isFocused() { - if ( - this.ScrollableNumericTextBoxColourRed.isFocused() || - this.ScrollableNumericTextBoxColourGreen.isFocused() || - this.ScrollableNumericTextBoxColourBlue.isFocused() - ) + if (this.ScrollableNumericTextBoxColourRed.isFocused() || this.ScrollableNumericTextBoxColourGreen.isFocused() || this.ScrollableNumericTextBoxColourBlue.isFocused()) { - return true; + return true; } return false; } - public boolean validateColorData() + public boolean validateColorData() { - return ( - (this.ScrollableNumericTextBoxColourRed.getText().length() > 0) && - (this.ScrollableNumericTextBoxColourGreen.getText().length() > 0) && - (this.ScrollableNumericTextBoxColourBlue.getText().length() > 0) - ); + return ((this.ScrollableNumericTextBoxColourRed.getText().length() > 0) && (this.ScrollableNumericTextBoxColourGreen.getText().length() > 0) && (this.ScrollableNumericTextBoxColourBlue.getText().length() > 0)); } - public int getColor() + public int getColor() { return this.colour; } - public void setColor(int colour) + public void setColor(int colour) { this.colour = colour; - + int red = (colour >> 16) & 0xff; - int green = (colour >> 8) & 0xff; - int blue = (colour) & 0xff; - int alpha = (colour >> 24) & 0xff; - - ScrollableNumericTextBoxColourRed.setText(red); - ScrollableNumericTextBoxColourGreen.setText(green); - ScrollableNumericTextBoxColourBlue.setText(blue); + int green = (colour >> 8) & 0xff; + int blue = (colour) & 0xff; + this.ScrollableNumericTextBoxColourRed.setText(red); + this.ScrollableNumericTextBoxColourGreen.setText(green); + this.ScrollableNumericTextBoxColourBlue.setText(blue); } private void UpdateColour() @@ -158,30 +114,30 @@ private void UpdateColour() colour += this.ScrollableNumericTextBoxColourRed.getTextFieldIntValue() << 16; colour += this.ScrollableNumericTextBoxColourGreen.getTextFieldIntValue() << 8; colour += this.ScrollableNumericTextBoxColourBlue.getTextFieldIntValue(); - this.colour = colour; + this.colour = colour; } - + @Override public void mouseClicked(int x, int y, int button) { super.mouseClicked(x, y, button); this.ScrollableNumericTextBoxColourRed.mouseClicked(x, y, button); this.ScrollableNumericTextBoxColourGreen.mouseClicked(x, y, button); - this.ScrollableNumericTextBoxColourBlue.mouseClicked(x, y, button); + this.ScrollableNumericTextBoxColourBlue.mouseClicked(x, y, button); } - - public void mouseDWheelScrolled(int x, int y, int direction) + + public void mouseDWheelScrolled(int x, int y, int direction) { // TODO Auto-generated method stub } - public void KeyTyped(char c, int key) + public void KeyTyped(char c, int key) { - this.ScrollableNumericTextBoxColourRed.KeyTyped(c, key); - this.ScrollableNumericTextBoxColourGreen.KeyTyped(c, key); - this.ScrollableNumericTextBoxColourBlue.KeyTyped(c, key); + this.ScrollableNumericTextBoxColourRed.KeyTyped(c, key); + this.ScrollableNumericTextBoxColourGreen.KeyTyped(c, key); + this.ScrollableNumericTextBoxColourBlue.KeyTyped(c, key); } - + @Override public void draw() { @@ -189,14 +145,14 @@ public void draw() this.ScrollableNumericTextBoxColourRed.draw(); this.ScrollableNumericTextBoxColourGreen.draw(); this.ScrollableNumericTextBoxColourBlue.draw(); - - UpdateColour(); - - this.drawRect(colourFieldX -1, colourFieldY-1, colourFieldX + colourFieldW + 1, colourFieldY + colourFieldH + 1, 0xff000000); - this.drawRect(colourFieldX, colourFieldY, colourFieldX + colourFieldW, colourFieldY + colourFieldH, this.colour); + + this.UpdateColour(); + + Gui.drawRect(this.colourFieldX - 1, this.colourFieldY - 1, this.colourFieldX + this.colourFieldW + 1, this.colourFieldY + this.colourFieldH + 1, 0xff000000); + Gui.drawRect(this.colourFieldX, this.colourFieldY, this.colourFieldX + this.colourFieldW, this.colourFieldY + this.colourFieldH, this.colour); } - public ScrollableField thisField() + public ScrollableField thisField() { if (this.ScrollableNumericTextBoxColourRed.isFocused()) { @@ -213,7 +169,7 @@ public ScrollableField thisField() return this.ScrollableNumericTextBoxColourRed; } - public ScrollableField nextField(ScrollableField field) + public ScrollableField nextField(ScrollableField field) { if (this.ScrollableNumericTextBoxColourRed.isFocused()) { @@ -226,7 +182,7 @@ public ScrollableField nextField(ScrollableField field) return field; } - public ScrollableField prevField(ScrollableField field) + public ScrollableField prevField(ScrollableField field) { if (this.ScrollableNumericTextBoxColourGreen.isFocused()) { diff --git a/src/main/java/mapwriter/gui/ScrollableField.java b/src/main/java/mapwriter/gui/ScrollableField.java index 3da6388a..fd8f85c8 100644 --- a/src/main/java/mapwriter/gui/ScrollableField.java +++ b/src/main/java/mapwriter/gui/ScrollableField.java @@ -12,111 +12,102 @@ public abstract class ScrollableField extends Gui public int x; public int y; public int width; - + public int labelX; public int labelY; public int labelWidth; public int labelHeight; public String label; - + private boolean drawArrows = false; private int leftArrowX; private int rightArrowX; private int arrowsY; public static int arrowsWidth = 7; private int arrowsHeight = 12; - + public final FontRenderer fontrendererObj; - + public ScrollableField(int x, int y, int width, String label, FontRenderer fontrendererObj) { this.x = x; this.y = y; this.width = width; - + this.fontrendererObj = fontrendererObj; this.label = label; - + this.leftArrowX = this.x + 1; this.rightArrowX = this.x + (this.width - ScrollableField.arrowsWidth); this.arrowsY = this.y; - + this.labelWidth = fontrendererObj.getStringWidth(this.label); this.labelHeight = this.fontrendererObj.FONT_HEIGHT; this.labelX = this.x - this.labelWidth; - this.labelY = this.y + this.labelHeight / 2 - 2; + this.labelY = (this.y + (this.labelHeight / 2)) - 2; } - + public void draw() { TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; - //Render.drawRectBorder(labelX, y, width + this.labelWidth + 4, this.arrowsHeight, 2); - - //draw the description label - drawString(this.fontrendererObj, this.label, this.labelX, this.labelY, 0xffffff); - - if (this.drawArrows) + // Render.drawRectBorder(labelX, y, width + this.labelWidth + 4, + // this.arrowsHeight, 2); + + // draw the description label + this.drawString(this.fontrendererObj, this.label, this.labelX, this.labelY, 0xffffff); + + if (this.drawArrows) { renderEngine.bindTexture(Reference.leftArrowTexture); - Render.drawTexturedRect( - this.leftArrowX, - this.arrowsY, - ScrollableField.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); + Render.drawTexturedRect(this.leftArrowX, this.arrowsY, ScrollableField.arrowsWidth, this.arrowsHeight, 0.0, 0.0, 1.0, 1.0); renderEngine.bindTexture(Reference.rightArrowTexture); - Render.drawTexturedRect( - this.rightArrowX, - this.arrowsY, - ScrollableField.arrowsWidth, - this.arrowsHeight, - 0.0, - 0.0, - 1.0, - 1.0 - ); + Render.drawTexturedRect(this.rightArrowX, this.arrowsY, ScrollableField.arrowsWidth, this.arrowsHeight, 0.0, 0.0, 1.0, 1.0); } } - - public void setDrawArrows(boolean value) { + + public void setDrawArrows(boolean value) + { this.drawArrows = value; } - public void mouseClicked(int x, int y, int button) { + public void mouseClicked(int x, int y, int button) + { int direction = this.posWithinArrows(x, y); if (direction == 1) { this.nextElement(); } - else if(direction == -1) + else if (direction == -1) { this.previousElement(); } } - + /** - * + * * @return Returns clicked arrow: 1 for right and -1 for left */ - public int posWithinArrows(int x, int y) { - if ((x >= this.leftArrowX) && (y >= this.arrowsY) - && (x <= ScrollableField.arrowsWidth + this.leftArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) + public int posWithinArrows(int x, int y) + { + if ((x >= this.leftArrowX) && (y >= this.arrowsY) && (x <= (ScrollableField.arrowsWidth + this.leftArrowX)) && (y <= (this.arrowsHeight + this.arrowsY))) + { return -1; - else if ((x >= this.rightArrowX) && (y >= this.arrowsY) - && (x <= ScrollableField.arrowsWidth + this.rightArrowX) - && (y <= this.arrowsHeight + this.arrowsY)) + } + else if ((x >= this.rightArrowX) && (y >= this.arrowsY) && (x <= (ScrollableField.arrowsWidth + this.rightArrowX)) && (y <= (this.arrowsHeight + this.arrowsY))) + { return 1; + } else + { return 0; + } } public abstract void nextElement(); + public abstract void previousElement(); + public abstract void setFocused(Boolean focus); + public abstract Boolean isFocused(); } diff --git a/src/main/java/mapwriter/gui/ScrollableTextBox.java b/src/main/java/mapwriter/gui/ScrollableTextBox.java index 2238ebdf..1334d105 100644 --- a/src/main/java/mapwriter/gui/ScrollableTextBox.java +++ b/src/main/java/mapwriter/gui/ScrollableTextBox.java @@ -1,250 +1,255 @@ -package mapwriter.gui; - -import java.util.List; - -import mapwriter.util.Reference; -import mapwriter.util.Render; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.renderer.texture.TextureManager; - -import org.lwjgl.input.Keyboard; - -public class ScrollableTextBox extends ScrollableField - { - public int textFieldX; - public int textFieldY; - public int textFieldWidth; - private static int textFieldHeight = 12; - - public List scrollableElements; - - protected GuiTextField textField; - - ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) - { - super(x, y, width, label, fontrendererObj); - this.init(); - } - - ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) - { - super(x, y, width, label, fontrendererObj); - this.scrollableElements = scrollableElements; - this.init(); - } - - private void init() - { - this.textFieldX = this.x + this.arrowsWidth + 3; - this.textFieldY = this.y; - this.textFieldWidth = this.width - 5 - ScrollableField.arrowsWidth * 2; - - textField = new GuiTextField( - 0, - this.fontrendererObj, - this.textFieldX, - this.textFieldY, - this.textFieldWidth, - this.textFieldHeight - ); - - textField.setMaxStringLength(32); - - } - - @Override - public void draw() - { - super.draw(); - this.textField.drawTextBox(); - if (!this.validateTextFieldData()) - { - //draw a red rectangle over the textbox to indicate that the text is invallid - int x1 = this.textFieldX - 1; - int y1 = this.textFieldY - 1; - int x2 = this.textFieldX + this.textFieldWidth; - int y2 = this.textFieldY + ScrollableTextBox.textFieldHeight; - int colour = 0xff900000; - - this.drawHorizontalLine(x1, x2, y1, colour); - this.drawHorizontalLine(x1, x2, y2, colour); - - this.drawVerticalLine(x1, y1, y2, colour); - this.drawVerticalLine(x2, y1, y2, colour); - } - } - - @Override - public void mouseClicked(int x, int y, int button) - { - super.mouseClicked(x, y, button); - this.textField.mouseClicked(x, y, button); - } - - public void mouseDWheelScrolled(int x, int y, int direction) { - if (posWithinTextField(x, y)) - textFieldScroll(-direction); - } - - public boolean validateTextFieldData() { - return this.getText().length() > 0; - } - - public boolean posWithinTextField(int x, int y) { - return (x >= this.textFieldX) && (y >= this.textFieldY) - && (x <= this.textFieldWidth + this.textFieldX) - && (y <= ScrollableTextBox.textFieldHeight + this.textFieldY); - } - - public void textFieldScroll(int direction) { - if (this.scrollableElements != null) { - int index = this.scrollableElements.indexOf( this.getText().trim()); - if (direction > 0) { - if (index == -1 - || index == this.scrollableElements.size() - 1) - index = 0; - else - index++; - } else if (direction < 0) { - if (index == -1 || index == 0) - index = this.scrollableElements.size() - 1; - else - index--; - } - this.textField.setText(this.scrollableElements.get(index)); - } - } - - @Override - public void nextElement() - { - this.textFieldScroll(1); - } - - @Override - public void previousElement() - { - this.textFieldScroll(-1); - } - - public String getText() - { - return this.textField.getText(); - } - - public void setText(String text) - { - this.textField.setText(text); - } - - public void setFocused(Boolean focus) - { - this.textField.setFocused(focus); - this.textField.setSelectionPos(0); - } - - public Boolean isFocused() - { - return this.textField.isFocused(); - } - - public void KeyTyped(char c, int key) - { - this.textField.textboxKeyTyped(c, key); - } - - public int getCursorPosition() - { - return this.textField.getCursorPosition(); - } - - public void setCursorPositionEnd() - { - this.textField.setCursorPositionEnd(); - } - } - -class ScrollableNumericTextBox extends ScrollableTextBox { - - public int maxValue = -1; - public int minValue = -1; - - public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) { - super(x, y, width, label, fontrendererObj); - } - - @Override - public void textFieldScroll(int direction) - { - int newValue = 0; - if (this.validateTextFieldData()) - { - newValue = this.getTextFieldIntValue(); - if (direction > 0) - { - if(this.maxValue < 0 || newValue + 1 <= this.maxValue) - { - newValue += 1; - } - } - else if (direction < 0) - { - if(this.minValue < 0 || newValue - 1 >= this.minValue) - { - newValue -= 1; - } - } - } - this.setText(newValue); - } - - public int getTextFieldIntValue() - { - try - { - return Integer.parseInt(this.getText()); - } - catch (NumberFormatException e) - { - return 0; - } - } - - public void setText(int num) - { - if(this.maxValue < 0 || num <= this.maxValue || num >= this.minValue ) - { - this.setText(Integer.toString(num)); - } - } - - @Override - public void KeyTyped(char c, int key) - { - if ((c >= '0' && c <= '9') || key == Keyboard.KEY_BACK - || key == Keyboard.KEY_LEFT || key == Keyboard.KEY_RIGHT - || (c == '-' && (this.getCursorPosition() == 0)) - ) - { - if (Character.isDigit(c) && (this.maxValue > -1 && Integer.parseInt(this.getText() + c) > this.maxValue)) - { - return; - } - super.KeyTyped(c, key); - } - } - - public void setMaxValue(int max) - { - this.maxValue = max; - this.textField.setMaxStringLength(Integer.toString(max).length()); - } - - public void setMinValue(int min) - { - this.minValue = min; - } -} - +package mapwriter.gui; + +import java.util.List; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiTextField; + +import org.lwjgl.input.Keyboard; + +public class ScrollableTextBox extends ScrollableField +{ + public int textFieldX; + public int textFieldY; + public int textFieldWidth; + private static int textFieldHeight = 12; + + public List scrollableElements; + + protected GuiTextField textField; + + ScrollableTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) + { + super(x, y, width, label, fontrendererObj); + this.init(); + } + + ScrollableTextBox(int x, int y, int width, String label, List scrollableElements, FontRenderer fontrendererObj) + { + super(x, y, width, label, fontrendererObj); + this.scrollableElements = scrollableElements; + this.init(); + } + + private void init() + { + this.textFieldX = this.x + ScrollableField.arrowsWidth + 3; + this.textFieldY = this.y; + this.textFieldWidth = this.width - 5 - (ScrollableField.arrowsWidth * 2); + + this.textField = new GuiTextField(0, this.fontrendererObj, this.textFieldX, this.textFieldY, this.textFieldWidth, ScrollableTextBox.textFieldHeight); + + this.textField.setMaxStringLength(32); + + } + + @Override + public void draw() + { + super.draw(); + this.textField.drawTextBox(); + if (!this.validateTextFieldData()) + { + // draw a red rectangle over the textbox to indicate that the text + // is invallid + int x1 = this.textFieldX - 1; + int y1 = this.textFieldY - 1; + int x2 = this.textFieldX + this.textFieldWidth; + int y2 = this.textFieldY + ScrollableTextBox.textFieldHeight; + int colour = 0xff900000; + + this.drawHorizontalLine(x1, x2, y1, colour); + this.drawHorizontalLine(x1, x2, y2, colour); + + this.drawVerticalLine(x1, y1, y2, colour); + this.drawVerticalLine(x2, y1, y2, colour); + } + } + + @Override + public void mouseClicked(int x, int y, int button) + { + super.mouseClicked(x, y, button); + this.textField.mouseClicked(x, y, button); + } + + public void mouseDWheelScrolled(int x, int y, int direction) + { + if (this.posWithinTextField(x, y)) + { + this.textFieldScroll(-direction); + } + } + + public boolean validateTextFieldData() + { + return this.getText().length() > 0; + } + + public boolean posWithinTextField(int x, int y) + { + return (x >= this.textFieldX) && (y >= this.textFieldY) && (x <= (this.textFieldWidth + this.textFieldX)) && (y <= (ScrollableTextBox.textFieldHeight + this.textFieldY)); + } + + public void textFieldScroll(int direction) + { + if (this.scrollableElements != null) + { + int index = this.scrollableElements.indexOf(this.getText().trim()); + if (direction > 0) + { + if ((index == -1) || (index == (this.scrollableElements.size() - 1))) + { + index = 0; + } + else + { + index++; + } + } + else if (direction < 0) + { + if ((index == -1) || (index == 0)) + { + index = this.scrollableElements.size() - 1; + } + else + { + index--; + } + } + this.textField.setText(this.scrollableElements.get(index)); + } + } + + @Override + public void nextElement() + { + this.textFieldScroll(1); + } + + @Override + public void previousElement() + { + this.textFieldScroll(-1); + } + + public String getText() + { + return this.textField.getText(); + } + + public void setText(String text) + { + this.textField.setText(text); + } + + @Override + public void setFocused(Boolean focus) + { + this.textField.setFocused(focus); + this.textField.setSelectionPos(0); + } + + @Override + public Boolean isFocused() + { + return this.textField.isFocused(); + } + + public void KeyTyped(char c, int key) + { + this.textField.textboxKeyTyped(c, key); + } + + public int getCursorPosition() + { + return this.textField.getCursorPosition(); + } + + public void setCursorPositionEnd() + { + this.textField.setCursorPositionEnd(); + } +} + +class ScrollableNumericTextBox extends ScrollableTextBox +{ + + public int maxValue = -1; + public int minValue = -1; + + public ScrollableNumericTextBox(int x, int y, int width, String label, FontRenderer fontrendererObj) + { + super(x, y, width, label, fontrendererObj); + } + + @Override + public void textFieldScroll(int direction) + { + int newValue = 0; + if (this.validateTextFieldData()) + { + newValue = this.getTextFieldIntValue(); + if (direction > 0) + { + if ((this.maxValue < 0) || ((newValue + 1) <= this.maxValue)) + { + newValue += 1; + } + } + else if (direction < 0) + { + if ((this.minValue < 0) || ((newValue - 1) >= this.minValue)) + { + newValue -= 1; + } + } + } + this.setText(newValue); + } + + public int getTextFieldIntValue() + { + try + { + return Integer.parseInt(this.getText()); + } + catch (NumberFormatException e) + { + return 0; + } + } + + public void setText(int num) + { + if ((this.maxValue < 0) || (num <= this.maxValue) || (num >= this.minValue)) + { + this.setText(Integer.toString(num)); + } + } + + @Override + public void KeyTyped(char c, int key) + { + if (((c >= '0') && (c <= '9')) || (key == Keyboard.KEY_BACK) || (key == Keyboard.KEY_LEFT) || (key == Keyboard.KEY_RIGHT) || ((c == '-') && (this.getCursorPosition() == 0))) + { + if (Character.isDigit(c) && ((this.maxValue > -1) && (Integer.parseInt(this.getText() + c) > this.maxValue))) + { + return; + } + super.KeyTyped(c, key); + } + } + + public void setMaxValue(int max) + { + this.maxValue = max; + this.textField.setMaxStringLength(Integer.toString(max).length()); + } + + public void setMinValue(int min) + { + this.minValue = min; + } +} diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index cf58cb78..d60c425f 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -16,41 +16,51 @@ import org.lwjgl.opengl.GL11; -public class MapRenderer { +public class MapRenderer +{ private Mw mw; private MapMode mapMode; private MapView mapView; // accessed by the MwGui to check whether the mouse cursor is near the // player arrow on the rendered map public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { + + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) + { this.mw = mw; this.mapMode = mapMode; this.mapView = mapView; } - - private void drawMap() { - + + private void drawMap() + { + int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) this.mw.textureSize; - double zoomScale = (double) (1 << regionZoomLevel); - - // if the texture UV coordinates do not line up with the texture pixels then the texture + double tSize = this.mw.textureSize; + double zoomScale = 1 << regionZoomLevel; + + // if the texture UV coordinates do not line up with the texture pixels + // then the texture // will look blurry when it is drawn to the screen. - // to fix this we round the texture coordinates to the nearest pixel boundary. - // this is unnecessary when zoomed in as the texture will be upscaled and look blurry + // to fix this we round the texture coordinates to the nearest pixel + // boundary. + // this is unnecessary when zoomed in as the texture will be upscaled + // and look blurry // anyway, so it is disabled in this case. - // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture + // also the rounding causes the map to noticeably (and unpleasantly) + // 'snap' to texture // pixel boundaries when zoomed in. - + double u, v, w, h; - if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + if ((!this.mapMode.config.circular) && (Config.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) + { u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; - } else { + } + else + { double tSizeInBlocks = tSize * zoomScale; u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; @@ -58,15 +68,18 @@ private void drawMap() { h = (this.mapView.getHeight() / tSizeInBlocks); } GlStateManager.pushMatrix(); - - if (this.mapMode.config.rotate && this.mapMode.config.circular == true) { + + if (this.mapMode.config.rotate && (this.mapMode.config.circular == true)) + { GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } - if (this.mapMode.config.circular) { + if (this.mapMode.config.circular) + { Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); } - - if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { + + if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) + { // draw the underground map this.mw.undergroundMapTexture.requestView(this.mapView); // underground map needs to have a black background @@ -74,139 +87,142 @@ private void drawMap() { Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); this.mw.undergroundMapTexture.bind(); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } else { + Render.drawTexturedRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, u, v, u + w, v + h); + } + else + { // draw the surface map MapViewRequest req = new MapViewRequest(this.mapView); this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); - + // draw the background texture if (!Config.backgroundTextureMode.equals(Config.backgroundModeStringArray[0])) - { - double bu1 = 0.0; double bu2 = 1.0; - double bv1 = 0.0; double bv2 = 1.0; + { + double bu1 = 0.0; + double bu2 = 1.0; + double bv1 = 0.0; + double bv2 = 1.0; if (Config.backgroundTextureMode.equals(Config.backgroundModeStringArray[2])) { // background moves with map if mode is 2 double bSize = tSize / 256.0; - bu1 = u * bSize; bu2 = (u + w) * bSize; - bv1 = v * bSize; bv2 = (v + h) * bSize; + bu1 = u * bSize; + bu2 = (u + w) * bSize; + bv1 = v * bSize; + bv2 = (v + h) * bSize; } this.mw.mc.renderEngine.bindTexture(Reference.backgroundTexture); Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - bu1, bv1, bu2, bv2 - ); - } else { + Render.drawTexturedRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, bu1, bv1, bu2, bv2); + } + else + { // mode 0, no background texture Render.setColourWithAlphaPercent(0x000000, this.mapMode.config.alphaPercent); Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); } - + // only draw surface map if the request is loaded (view requests are // loaded by the background thread) - if (this.mw.mapTexture.isLoaded(req)) { + if (this.mw.mapTexture.isLoaded(req)) + { this.mw.mapTexture.bind(); Render.setColourWithAlphaPercent(0xffffff, this.mapMode.config.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); + Render.drawTexturedRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, u, v, u + w, v + h); } } - + // draw ProfMobius chunk overlay IMwDataProvider provider = this.drawOverlay(); - + // overlay onDraw event - if (provider != null) { - GlStateManager.pushMatrix(); + if (provider != null) + { + GlStateManager.pushMatrix(); provider.onDraw(this.mapView, this.mapMode); GlStateManager.popMatrix(); } - - if (this.mapMode.config.circular) { + + if (this.mapMode.config.circular) + { Render.disableStencil(); } GlStateManager.popMatrix(); } - - private void drawBorder() { - if (this.mapMode.config.circular) { + + private void drawBorder() + { + if (this.mapMode.config.circular) + { this.mw.mc.renderEngine.bindTexture(Reference.roundMapTexture); - } else { + } + else + { this.mw.mc.renderEngine.bindTexture(Reference.squareMapTexture); } Render.setColour(0xffffffff); - Render.drawTexturedRect( - this.mapMode.x / 0.75, this.mapMode.y / 0.75, - this.mapMode.w / 0.75, this.mapMode.h / 0.75, - 0.0, 0.0, 1.0, 1.0 - ); + Render.drawTexturedRect(this.mapMode.x / 0.75, this.mapMode.y / 0.75, this.mapMode.w / 0.75, this.mapMode.h / 0.75, 0.0, 0.0, 1.0, 1.0); } - - private void drawPlayerArrow() { + + private void drawPlayerArrow() + { GlStateManager.pushMatrix(); double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); - + // the arrow only needs to be rotated if the map is NOT rotated GlStateManager.translate(p.x, p.y, 0.0); - if (!this.mapMode.config.rotate || this.mapMode.config.circular == false) { + if (!this.mapMode.config.rotate || (this.mapMode.config.circular == false)) + { GlStateManager.rotate(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } - + double arrowSize = this.mapMode.config.playerArrowSize; Render.setColour(0xffffffff); this.mw.mc.renderEngine.bindTexture(Reference.playerArrowTexture); - Render.drawTexturedRect( - -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); + Render.drawTexturedRect(-arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, 0.0, 0.0, 1.0, 1.0); GlStateManager.popMatrix(); } - - private void drawIcons() { + + private void drawIcons() + { GlStateManager.pushMatrix(); - - if (this.mapMode.config.rotate && this.mapMode.config.circular == true) { + + if (this.mapMode.config.rotate && (this.mapMode.config.circular == true)) + { GlStateManager.rotate(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); } - + // draw markers this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); - + // draw player trail - if (this.mw.playerTrail.enabled) { + if (this.mw.playerTrail.enabled) + { this.mw.playerTrail.draw(this.mapMode, this.mapView); } - + // draw north arrow - if (this.mapMode.config.rotate) { + if (this.mapMode.config.rotate) + { double y = this.mapMode.h / 2.0; double arrowSize = this.mapMode.config.playerArrowSize; Render.setColour(0xffffffff); this.mw.mc.renderEngine.bindTexture(Reference.northArrowTexture); - Render.drawTexturedRect( - -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); + Render.drawTexturedRect(-arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, 0.0, 0.0, 1.0, 1.0); } GlStateManager.popMatrix(); - + // outside of the matrix pop as theplayer arrow // needs to be drawn without rotation this.drawPlayerArrow(); } - - private void drawCoords() { + + private void drawCoords() + { // draw coordinates - if (!this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[0])) + if (!this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[0])) { GlStateManager.pushMatrix(); GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); @@ -215,106 +231,102 @@ private void drawCoords() { GlStateManager.scale(0.5f, 0.5f, 1.0f); } int offset = 0; - Render.drawCentredString(0, 0, this.mapMode.textColour, - "%d, %d, %d", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt - ); - offset += 12; - if (Config.undergroundMode) { - Render.drawCentredString( - 0, offset, this.mapMode.textColour,"underground mode" - ); + Render.drawCentredString(0, 0, this.mapMode.textColour, "%d, %d, %d", this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); + offset += 12; + if (Config.undergroundMode) + { + Render.drawCentredString(0, offset, this.mapMode.textColour, "underground mode"); } GlStateManager.popMatrix(); } } - - private IMwDataProvider drawOverlay() { + + private IMwDataProvider drawOverlay() + { // draw overlays from registered providers - //for (IMwDataProvider provider : MwAPI.getDataProviders()) + // for (IMwDataProvider provider : MwAPI.getDataProviders()) IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) { - ArrayList overlays = provider.getChunksOverlay( - this.mapView.getDimension(), - this.mapView.getX(), this.mapView.getZ(), - this.mapView.getMinX(), this.mapView.getMinZ(), - this.mapView.getMaxX(), this.mapView.getMaxZ() - ); - if (overlays != null) { - for (IMwChunkOverlay overlay : overlays) { - paintChunk(this.mapMode, this.mapView, overlay); - } + if (provider != null) + { + ArrayList overlays = provider.getChunksOverlay(this.mapView.getDimension(), this.mapView.getX(), this.mapView.getZ(), this.mapView.getMinX(), this.mapView.getMinZ(), this.mapView.getMaxX(), this.mapView.getMaxZ()); + if (overlays != null) + { + for (IMwChunkOverlay overlay : overlays) + { + paintChunk(this.mapMode, this.mapView, overlay); + } } } return provider; } - - public void draw() { + + public void draw() + { this.mapMode.updateMargin(); this.mapMode.setScreenRes(); this.mapView.setMapWH(this.mapMode); this.mapView.setTextureSize(this.mw.textureSize); - + GlStateManager.pushMatrix(); GlStateManager.loadIdentity(); - + // translate to center of minimap // z is -2000 so that it is drawn above the 3D world, but below GUI // elements which are typically at -3000 GlStateManager.translate(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); - + // draw background, the map texture, and enabled overlays this.drawMap(); - - if (this.mapMode.config.borderMode) { + + if (this.mapMode.config.borderMode) + { this.drawBorder(); } this.drawIcons(); - + this.drawCoords(); - + // some shader mods seem to need depth testing re-enabled GL11.glEnable(GL11.GL_DEPTH_TEST); GlStateManager.popMatrix(); } - - private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ - int chunkX = overlay.getCoordinates().x; - int chunkZ = overlay.getCoordinates().y; + + private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay) + { + int chunkX = overlay.getCoordinates().x; + int chunkZ = overlay.getCoordinates().y; float filling = overlay.getFilling(); - + Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); - Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); + Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, ((chunkZ + 1) << 4)); - topCorner.x = Math.max(mapMode.x, topCorner.x); + topCorner.x = Math.max(mapMode.x, topCorner.x); topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); - topCorner.y = Math.max(mapMode.y, topCorner.y); + topCorner.y = Math.max(mapMode.y, topCorner.y); topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); - - botCorner.x = Math.max(mapMode.x, botCorner.x); + + botCorner.x = Math.max(mapMode.x, botCorner.x); botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); - botCorner.y = Math.max(mapMode.y, botCorner.y); - botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); + botCorner.y = Math.max(mapMode.y, botCorner.y); + botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); double sizeX = (botCorner.x - topCorner.x) * filling; - double sizeY = (botCorner.y - topCorner.y) * filling; + double sizeY = (botCorner.y - topCorner.y) * filling; double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; - double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; - - if (overlay.hasBorder()) { + double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; + + if (overlay.hasBorder()) + { Render.setColour(overlay.getBorderColor()); Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); } - + Render.setColour(overlay.getColor()); Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); } public MapMode getMapMode() { - return this.mapMode; + return this.mapMode; } } - diff --git a/src/main/java/mapwriter/map/MapTexture.java b/src/main/java/mapwriter/map/MapTexture.java index 33b67ac8..f0f406b4 100644 --- a/src/main/java/mapwriter/map/MapTexture.java +++ b/src/main/java/mapwriter/map/MapTexture.java @@ -1,169 +1,202 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.BackgroundExecutor; -import mapwriter.region.Region; -import mapwriter.region.RegionManager; -import mapwriter.util.Texture; - -import org.lwjgl.opengl.GL11; - -public class MapTexture extends Texture { - - public int textureRegions; - public int textureSize; - - private MapViewRequest loadedView = null; - private MapViewRequest requestedView = null; - - private Region[] regionArray; - - // accessed from both render and background thread. - // make sure all methods using it are synchronized. - //private int[] regionModifiedArray; - - private class Rect { - final int x, y, w, h; - Rect(int x, int y, int w, int h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - } - - private List textureUpdateQueue = new ArrayList(); - - public MapTexture(int textureSize, boolean linearScaling) { - super(textureSize, textureSize, 0x00000000, GL11.GL_LINEAR, GL11.GL_LINEAR, GL11.GL_REPEAT); - - this.setLinearScaling(linearScaling); - - this.textureRegions = textureSize >> Region.SHIFT; - this.textureSize = textureSize; - this.regionArray = new Region[this.textureRegions * this.textureRegions]; - } - - public void requestView(MapViewRequest req, BackgroundExecutor executor, RegionManager regionManager) { - if ((this.requestedView == null) || (!this.requestedView.equals(req))) { - this.requestedView = req; - executor.addTask(new MapUpdateViewTask(this, regionManager, req)); - } - } - - public void processTextureUpdates() { - synchronized (this.textureUpdateQueue) { - for (Rect rect : this.textureUpdateQueue) { - //MwUtil.log("MwMapTexture.processTextureUpdates: %d %d %d %d", rect.x, rect.y, rect.w, rect.h); - this.updateTextureArea(rect.x, rect.y, rect.w, rect.h); - } - this.textureUpdateQueue.clear(); - } - } - - public void setLoaded(MapViewRequest req) { - this.loadedView = req; - } - - public boolean isLoaded(MapViewRequest req) { - return (this.loadedView != null) && (this.loadedView.mostlyEquals(req)); - } - - // - // methods below this point run in the background thread - // - - public synchronized void setRGBOpaque(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { - // TODO: Remove the need for this function. It would better if the - // region pixels were stored as normal pixels (without the height in - // the alpha channel). Then we could just directly copy the pixels - // to the texture pixelBuf. - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - this.setPixelBufPosition(bufOffset + (i * this.w)); - int rowOffset = offset + (i * scanSize); - for (int j = 0; j < w; j++) { - int colour = pixels[rowOffset + j]; - if(colour != 0) { - colour |= 0xff000000; - } - this.pixelBufPut(colour); - } - } - } - - public void addTextureUpdate(int x, int z, int w, int h) { - synchronized (this.textureUpdateQueue) { - this.textureUpdateQueue.add(new Rect(x, z, w, h)); - } - } - - public void updateTextureFromRegion(Region region, int x, int z, int w, int h) { - int tx = (x >> region.zoomLevel) & (this.w - 1); - int ty = (z >> region.zoomLevel) & (this.h - 1); - int tw = (w >> region.zoomLevel); - int th = (h >> region.zoomLevel); - - // make sure we don't write outside texture - tw = Math.min(tw, this.w - tx); - th = Math.min(th, this.h - th); - - //MwUtil.log("updateTextureFromRegion: region %s, %d %d %d %d -> %d %d %d %d", region, x, z, w, h, tx, ty, tw, th); - - int[] pixels = region.getPixels(); - if (pixels != null) { - this.setRGBOpaque(tx, ty, tw, th, pixels, region.getPixelOffset(x, z), Region.SIZE); - } else { - this.fillRect(tx, ty, tw, th, 0x00000000); - } - - this.addTextureUpdate(tx, ty, tw, th); - } - - public int getRegionIndex(int x, int z, int zoomLevel) { - x = (x >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); - z = (z >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); - return (z * this.textureRegions) + x; - } - - public boolean loadRegion(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { - //MwUtil.log("mapTexture.loadRegion %d %d %d %d", x, z, zoomLevel, dimension); - boolean loaded = false; - int index = this.getRegionIndex(x, z, zoomLevel); - Region currentRegion = this.regionArray[index]; - if ((currentRegion == null) || (!currentRegion.equals(x, z, zoomLevel, dimension))) { - Region newRegion = regionManager.getRegion(x, z, zoomLevel, dimension); - this.regionArray[index] = newRegion; - this.updateTextureFromRegion( - newRegion, newRegion.x, newRegion.z, newRegion.size, newRegion.size - ); - //regionManager.logInfo("regionArray[%d] = %s", index, newRegion); - loaded = true; - } - return loaded; - } - - public int loadRegions(RegionManager regionManager, MapViewRequest req) { - int size = Region.SIZE << req.zoomLevel; - int loadedCount = 0; - for (int z = req.zMin; z <= req.zMax; z += size) { - for (int x = req.xMin; x <= req.xMax; x += size) { - if (this.loadRegion(regionManager, x, z, req.zoomLevel, req.dimension)) { - loadedCount++; - } - } - } - return loadedCount; - } - - public void updateArea(RegionManager regionManager, int x, int z, int w, int h, int dimension) { - for (int i = 0; i < this.regionArray.length; i++) { - Region region = this.regionArray[i]; - if ((region != null) && (region.isAreaWithin(x, z, w, h, dimension))) { - this.updateTextureFromRegion(region, x, z, w, h); - } - } - } -} +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.BackgroundExecutor; +import mapwriter.region.Region; +import mapwriter.region.RegionManager; +import mapwriter.util.Texture; + +import org.lwjgl.opengl.GL11; + +public class MapTexture extends Texture +{ + + public int textureRegions; + public int textureSize; + + private MapViewRequest loadedView = null; + private MapViewRequest requestedView = null; + + private Region[] regionArray; + + // accessed from both render and background thread. + // make sure all methods using it are synchronized. + // private int[] regionModifiedArray; + + private class Rect + { + final int x, y, w, h; + + Rect(int x, int y, int w, int h) + { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + } + + private List textureUpdateQueue = new ArrayList(); + + public MapTexture(int textureSize, boolean linearScaling) + { + super(textureSize, textureSize, 0x00000000, GL11.GL_LINEAR, GL11.GL_LINEAR, GL11.GL_REPEAT); + + this.setLinearScaling(linearScaling); + + this.textureRegions = textureSize >> Region.SHIFT; + this.textureSize = textureSize; + this.regionArray = new Region[this.textureRegions * this.textureRegions]; + } + + public void requestView(MapViewRequest req, BackgroundExecutor executor, RegionManager regionManager) + { + if ((this.requestedView == null) || (!this.requestedView.equals(req))) + { + this.requestedView = req; + executor.addTask(new MapUpdateViewTask(this, regionManager, req)); + } + } + + public void processTextureUpdates() + { + synchronized (this.textureUpdateQueue) + { + for (Rect rect : this.textureUpdateQueue) + { + // MwUtil.log("MwMapTexture.processTextureUpdates: %d %d %d %d", + // rect.x, rect.y, rect.w, rect.h); + this.updateTextureArea(rect.x, rect.y, rect.w, rect.h); + } + this.textureUpdateQueue.clear(); + } + } + + public void setLoaded(MapViewRequest req) + { + this.loadedView = req; + } + + public boolean isLoaded(MapViewRequest req) + { + return (this.loadedView != null) && (this.loadedView.mostlyEquals(req)); + } + + // + // methods below this point run in the background thread + // + + public synchronized void setRGBOpaque(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) + { + // TODO: Remove the need for this function. It would better if the + // region pixels were stored as normal pixels (without the height in + // the alpha channel). Then we could just directly copy the pixels + // to the texture pixelBuf. + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) + { + this.setPixelBufPosition(bufOffset + (i * this.w)); + int rowOffset = offset + (i * scanSize); + for (int j = 0; j < w; j++) + { + int colour = pixels[rowOffset + j]; + if (colour != 0) + { + colour |= 0xff000000; + } + this.pixelBufPut(colour); + } + } + } + + public void addTextureUpdate(int x, int z, int w, int h) + { + synchronized (this.textureUpdateQueue) + { + this.textureUpdateQueue.add(new Rect(x, z, w, h)); + } + } + + public void updateTextureFromRegion(Region region, int x, int z, int w, int h) + { + int tx = (x >> region.zoomLevel) & (this.w - 1); + int ty = (z >> region.zoomLevel) & (this.h - 1); + int tw = (w >> region.zoomLevel); + int th = (h >> region.zoomLevel); + + // make sure we don't write outside texture + tw = Math.min(tw, this.w - tx); + th = Math.min(th, this.h - th); + + // MwUtil.log("updateTextureFromRegion: region %s, %d %d %d %d -> %d %d %d %d", + // region, x, z, w, h, tx, ty, tw, th); + + int[] pixels = region.getPixels(); + if (pixels != null) + { + this.setRGBOpaque(tx, ty, tw, th, pixels, region.getPixelOffset(x, z), Region.SIZE); + } + else + { + this.fillRect(tx, ty, tw, th, 0x00000000); + } + + this.addTextureUpdate(tx, ty, tw, th); + } + + public int getRegionIndex(int x, int z, int zoomLevel) + { + x = (x >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); + z = (z >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); + return (z * this.textureRegions) + x; + } + + public boolean loadRegion(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) + { + // MwUtil.log("mapTexture.loadRegion %d %d %d %d", x, z, zoomLevel, + // dimension); + boolean loaded = false; + int index = this.getRegionIndex(x, z, zoomLevel); + Region currentRegion = this.regionArray[index]; + if ((currentRegion == null) || (!currentRegion.equals(x, z, zoomLevel, dimension))) + { + Region newRegion = regionManager.getRegion(x, z, zoomLevel, dimension); + this.regionArray[index] = newRegion; + this.updateTextureFromRegion(newRegion, newRegion.x, newRegion.z, newRegion.size, newRegion.size); + // regionManager.logInfo("regionArray[%d] = %s", index, newRegion); + loaded = true; + } + return loaded; + } + + public int loadRegions(RegionManager regionManager, MapViewRequest req) + { + int size = Region.SIZE << req.zoomLevel; + int loadedCount = 0; + for (int z = req.zMin; z <= req.zMax; z += size) + { + for (int x = req.xMin; x <= req.xMax; x += size) + { + if (this.loadRegion(regionManager, x, z, req.zoomLevel, req.dimension)) + { + loadedCount++; + } + } + } + return loadedCount; + } + + public void updateArea(RegionManager regionManager, int x, int z, int w, int h, int dimension) + { + for (int i = 0; i < this.regionArray.length; i++) + { + Region region = this.regionArray[i]; + if ((region != null) && (region.isAreaWithin(x, z, w, h, dimension))) + { + this.updateTextureFromRegion(region, x, z, w, h); + } + } + } +} diff --git a/src/main/java/mapwriter/map/MapUpdateViewTask.java b/src/main/java/mapwriter/map/MapUpdateViewTask.java index 4a910425..4fb7b77e 100644 --- a/src/main/java/mapwriter/map/MapUpdateViewTask.java +++ b/src/main/java/mapwriter/map/MapUpdateViewTask.java @@ -3,28 +3,33 @@ import mapwriter.region.RegionManager; import mapwriter.tasks.Task; -public class MapUpdateViewTask extends Task { +public class MapUpdateViewTask extends Task +{ final MapViewRequest req; RegionManager regionManager; MapTexture mapTexture; - + // chunkmanager will need to keep a list of chunks to update. - // it should also keep a 2D chunkSum array so that only modified chunks are updated. - public MapUpdateViewTask(MapTexture mapTexture, RegionManager regionManager, MapViewRequest req) { - + // it should also keep a 2D chunkSum array so that only modified chunks are + // updated. + public MapUpdateViewTask(MapTexture mapTexture, RegionManager regionManager, MapViewRequest req) + { + this.mapTexture = mapTexture; this.regionManager = regionManager; this.req = req; } - + @Override - public void run() { + public void run() + { // load regions for view this.mapTexture.loadRegions(this.regionManager, this.req); } - + @Override - public void onComplete() { + public void onComplete() + { // set currentView in mapTexture to requestedView this.mapTexture.setLoaded(this.req); } diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java index 9418c4f1..97ec62e5 100644 --- a/src/main/java/mapwriter/map/MapView.java +++ b/src/main/java/mapwriter/map/MapView.java @@ -1,285 +1,345 @@ -package mapwriter.map; - -import java.util.List; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.config.Config; -import mapwriter.map.mapmode.MapMode; - -public class MapView { - - private int zoomLevel = 0; - private int dimension = 0; - private int textureSize = 2048; - - // the position of the centre of the 'view' of the map using game (block) coordinates - private double x = 0; - private double z = 0; - - // width and height of map to display in pixels - private int mapW = 0; - private int mapH = 0; - - // the width and height of the map in blocks at zoom level 0. - // updated when map width, map height, or texture size changes. - private int baseW = 1; - private int baseH = 1; - - // the width and height of the map in blocks at the current - // zoom level. - private double w = 1; - private double h = 1; - - private int minZoom; - private int maxZoom; - - private boolean undergroundMode; - private boolean fullscreenMap; - - public MapView(Mw mw, boolean FullscreenMap) { - this.minZoom = Config.zoomInLevels; - this.maxZoom = Config.zoomOutLevels; - this.undergroundMode = Config.undergroundMode; - this.fullscreenMap = FullscreenMap; - if (this.fullscreenMap) - { - this.setZoomLevel(Config.fullScreenZoomLevel); - } - this.setZoomLevel(Config.overlayZoomLevel); - this.setViewCentre(mw.playerX, mw.playerZ); - } - - public void setViewCentre(double vX, double vZ) { - this.x = vX; - this.z = vZ; - - if (MwAPI.getCurrentDataProvider() != null) { - MwAPI.getCurrentDataProvider().onMapCenterChanged(vX, vZ, this); - } - - } - - public double getX() { - return this.x; - } - - public double getZ() { - return this.z; - } - - public double getWidth() { - return this.w; - } - - public double getHeight() { - return this.h; - } - - public void panView(double relX, double relZ) { - this.setViewCentre( - this.x + (relX * this.w), - this.z + (relZ * this.h) - ); - } - - public int setZoomLevel(int zoomLevel) { - //MwUtil.log("MapView.setZoomLevel(%d)", zoomLevel); - int prevZoomLevel = this.zoomLevel; - if (this.undergroundMode) { - this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), 0); - } else { - this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), this.maxZoom); - } - if (prevZoomLevel != this.zoomLevel) { - this.updateZoom(); - } - - if (this.fullscreenMap) - { - Config.fullScreenZoomLevel = this.zoomLevel; - } - Config.overlayZoomLevel = this.zoomLevel; - - return this.zoomLevel; - } - - private void updateZoom() { - if (this.zoomLevel >= 0) { - this.w = this.baseW << this.zoomLevel; - this.h = this.baseH << this.zoomLevel; - } else { - this.w = this.baseW >> (-this.zoomLevel); - this.h = this.baseH >> (-this.zoomLevel); - } - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onZoomChanged(this.getZoomLevel(), this); - } - - public int adjustZoomLevel(int n) { - return this.setZoomLevel(this.zoomLevel + n); - } - - public int getZoomLevel() { - return this.zoomLevel; - } - - public int getRegionZoomLevel() { - return Math.max(0, this.zoomLevel); - } - - // bX and bZ are the coordinates of the block the zoom is centred on. - // The relative position of the block in the view will remain the same - // as before the zoom. - public void zoomToPoint(int newZoomLevel, double bX, double bZ) { - int prevZoomLevel = this.zoomLevel; - newZoomLevel = this.setZoomLevel(newZoomLevel); - double zF = Math.pow(2, newZoomLevel - prevZoomLevel); - this.setViewCentre( - bX - ((bX - this.x) * zF), - bZ - ((bZ - this.z) * zF)); - } - - public void setDimension(int dimension) { - double scale = 1.0; - if (dimension != this.dimension) { - if ((this.dimension != -1) && (dimension == -1)) { - scale = 0.125; - } else if ((this.dimension == -1) && (dimension != -1)) { - scale = 8.0; - } - this.dimension = dimension; - this.setViewCentre(this.x * scale, this.z * scale); - } - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onDimensionChanged(this.dimension, this); - } - - public void setDimensionAndAdjustZoom(int dimension) { - int zoomLevelChange = 0; - if ((this.dimension != -1) && (dimension == -1)) { - zoomLevelChange = -3; - } else if ((this.dimension == -1) && (dimension != -1)) { - zoomLevelChange = 3; - } - this.setZoomLevel(this.getZoomLevel() + zoomLevelChange); - this.setDimension(dimension); - } - - public void nextDimension(List dimensionList, int n) { - int i = dimensionList.indexOf(this.dimension); - i = Math.max(0, i); - int size = dimensionList.size(); - int dimension = dimensionList.get((i + size + n) % size); - this.setDimensionAndAdjustZoom(dimension); - } - - public int getDimension() { - return this.dimension; - } - - public void setMapWH(int w, int h) { - if ((this.mapW != w) || (this.mapH != h)) { - this.mapW = w; - this.mapH = h; - this.updateBaseWH(); - } - } - - public void setMapWH(MapMode mapMode) { - this.setMapWH(mapMode.wPixels, mapMode.hPixels); - } - - public double getMinX() { - return this.x - (this.w / 2); - } - - public double getMaxX() { - return this.x + (this.w / 2); - } - - public double getMinZ() { - return this.z - (this.h / 2); - } - - public double getMaxZ() { - return this.z + (this.h / 2); - } - - public double getDimensionScaling(int playerDimension) { - double scale; - if ((this.dimension != -1) && (playerDimension == -1)) { - scale = 8.0; - } else if ((this.dimension == -1) && (playerDimension != -1)) { - scale = 0.125; - } else { - scale = 1.0; - } - return scale; - } - - public void setViewCentreScaled(double vX, double vZ, int playerDimension) { - double scale = this.getDimensionScaling(playerDimension); - this.setViewCentre(vX * scale, vZ * scale); - } - - public void setTextureSize(int n) { - if (this.textureSize != n) { - this.textureSize = n; - this.updateBaseWH(); - } - } - - private void updateBaseWH() { - int w = this.mapW; - int h = this.mapH; - int halfTextureSize = this.textureSize / 2; - - // if we cannot display the map at 1x1 pixel per block, then - // try 2x2 pixels per block, then 4x4 and so on - while ((w > halfTextureSize) || (h > halfTextureSize)) { - w /= 2; - h /= 2; - } - - //MwUtil.log("MapView.updateBaseWH: map = %dx%d, tsize = %d, base = %dx%d", this.mapW, this.mapH, this.textureSize, w, h); - - this.baseW = w; - this.baseH = h; - - this.updateZoom(); - } - - public int getPixelsPerBlock() { - return this.mapW / this.baseW; - } - - public boolean isBlockWithinView(double bX, double bZ, boolean circular) { - boolean inside; - if (!circular) { - inside = (bX > this.getMinX()) || (bX < this.getMaxX()) || - (bZ > this.getMinZ()) || (bZ < this.getMaxZ()); - } else { - double x = (bX - this.x); - double z = (bZ - this.z); - double r = this.getHeight() / 2; - inside = ((x * x) + (z * z)) < (r * r); - } - return inside; - } - - public boolean getUndergroundMode() { - return this.undergroundMode; - } - - public void setUndergroundMode(boolean enabled) { - if (enabled) { - if (this.zoomLevel >= 0) { - this.setZoomLevel(-1); - } - } - this.undergroundMode = enabled; - } -} +package mapwriter.map; + +import java.util.List; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.config.Config; +import mapwriter.map.mapmode.MapMode; + +public class MapView +{ + + private int zoomLevel = 0; + private int dimension = 0; + private int textureSize = 2048; + + // the position of the centre of the 'view' of the map using game (block) + // coordinates + private double x = 0; + private double z = 0; + + // width and height of map to display in pixels + private int mapW = 0; + private int mapH = 0; + + // the width and height of the map in blocks at zoom level 0. + // updated when map width, map height, or texture size changes. + private int baseW = 1; + private int baseH = 1; + + // the width and height of the map in blocks at the current + // zoom level. + private double w = 1; + private double h = 1; + + private int minZoom; + private int maxZoom; + + private boolean undergroundMode; + private boolean fullscreenMap; + + public MapView(Mw mw, boolean FullscreenMap) + { + this.minZoom = Config.zoomInLevels; + this.maxZoom = Config.zoomOutLevels; + this.undergroundMode = Config.undergroundMode; + this.fullscreenMap = FullscreenMap; + if (this.fullscreenMap) + { + this.setZoomLevel(Config.fullScreenZoomLevel); + } + this.setZoomLevel(Config.overlayZoomLevel); + this.setViewCentre(mw.playerX, mw.playerZ); + } + + public void setViewCentre(double vX, double vZ) + { + this.x = vX; + this.z = vZ; + + if (MwAPI.getCurrentDataProvider() != null) + { + MwAPI.getCurrentDataProvider().onMapCenterChanged(vX, vZ, this); + } + + } + + public double getX() + { + return this.x; + } + + public double getZ() + { + return this.z; + } + + public double getWidth() + { + return this.w; + } + + public double getHeight() + { + return this.h; + } + + public void panView(double relX, double relZ) + { + this.setViewCentre(this.x + (relX * this.w), this.z + (relZ * this.h)); + } + + public int setZoomLevel(int zoomLevel) + { + // MwUtil.log("MapView.setZoomLevel(%d)", zoomLevel); + int prevZoomLevel = this.zoomLevel; + if (this.undergroundMode) + { + this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), 0); + } + else + { + this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), this.maxZoom); + } + if (prevZoomLevel != this.zoomLevel) + { + this.updateZoom(); + } + + if (this.fullscreenMap) + { + Config.fullScreenZoomLevel = this.zoomLevel; + } + Config.overlayZoomLevel = this.zoomLevel; + + return this.zoomLevel; + } + + private void updateZoom() + { + if (this.zoomLevel >= 0) + { + this.w = this.baseW << this.zoomLevel; + this.h = this.baseH << this.zoomLevel; + } + else + { + this.w = this.baseW >> (-this.zoomLevel); + this.h = this.baseH >> (-this.zoomLevel); + } + + if (MwAPI.getCurrentDataProvider() != null) + { + MwAPI.getCurrentDataProvider().onZoomChanged(this.getZoomLevel(), this); + } + } + + public int adjustZoomLevel(int n) + { + return this.setZoomLevel(this.zoomLevel + n); + } + + public int getZoomLevel() + { + return this.zoomLevel; + } + + public int getRegionZoomLevel() + { + return Math.max(0, this.zoomLevel); + } + + // bX and bZ are the coordinates of the block the zoom is centred on. + // The relative position of the block in the view will remain the same + // as before the zoom. + public void zoomToPoint(int newZoomLevel, double bX, double bZ) + { + int prevZoomLevel = this.zoomLevel; + newZoomLevel = this.setZoomLevel(newZoomLevel); + double zF = Math.pow(2, newZoomLevel - prevZoomLevel); + this.setViewCentre(bX - ((bX - this.x) * zF), bZ - ((bZ - this.z) * zF)); + } + + public void setDimension(int dimension) + { + double scale = 1.0; + if (dimension != this.dimension) + { + if ((this.dimension != -1) && (dimension == -1)) + { + scale = 0.125; + } + else if ((this.dimension == -1) && (dimension != -1)) + { + scale = 8.0; + } + this.dimension = dimension; + this.setViewCentre(this.x * scale, this.z * scale); + } + + if (MwAPI.getCurrentDataProvider() != null) + { + MwAPI.getCurrentDataProvider().onDimensionChanged(this.dimension, this); + } + } + + public void setDimensionAndAdjustZoom(int dimension) + { + int zoomLevelChange = 0; + if ((this.dimension != -1) && (dimension == -1)) + { + zoomLevelChange = -3; + } + else if ((this.dimension == -1) && (dimension != -1)) + { + zoomLevelChange = 3; + } + this.setZoomLevel(this.getZoomLevel() + zoomLevelChange); + this.setDimension(dimension); + } + + public void nextDimension(List dimensionList, int n) + { + int i = dimensionList.indexOf(this.dimension); + i = Math.max(0, i); + int size = dimensionList.size(); + int dimension = dimensionList.get((i + size + n) % size); + this.setDimensionAndAdjustZoom(dimension); + } + + public int getDimension() + { + return this.dimension; + } + + public void setMapWH(int w, int h) + { + if ((this.mapW != w) || (this.mapH != h)) + { + this.mapW = w; + this.mapH = h; + this.updateBaseWH(); + } + } + + public void setMapWH(MapMode mapMode) + { + this.setMapWH(mapMode.wPixels, mapMode.hPixels); + } + + public double getMinX() + { + return this.x - (this.w / 2); + } + + public double getMaxX() + { + return this.x + (this.w / 2); + } + + public double getMinZ() + { + return this.z - (this.h / 2); + } + + public double getMaxZ() + { + return this.z + (this.h / 2); + } + + public double getDimensionScaling(int playerDimension) + { + double scale; + if ((this.dimension != -1) && (playerDimension == -1)) + { + scale = 8.0; + } + else if ((this.dimension == -1) && (playerDimension != -1)) + { + scale = 0.125; + } + else + { + scale = 1.0; + } + return scale; + } + + public void setViewCentreScaled(double vX, double vZ, int playerDimension) + { + double scale = this.getDimensionScaling(playerDimension); + this.setViewCentre(vX * scale, vZ * scale); + } + + public void setTextureSize(int n) + { + if (this.textureSize != n) + { + this.textureSize = n; + this.updateBaseWH(); + } + } + + private void updateBaseWH() + { + int w = this.mapW; + int h = this.mapH; + int halfTextureSize = this.textureSize / 2; + + // if we cannot display the map at 1x1 pixel per block, then + // try 2x2 pixels per block, then 4x4 and so on + while ((w > halfTextureSize) || (h > halfTextureSize)) + { + w /= 2; + h /= 2; + } + + // MwUtil.log("MapView.updateBaseWH: map = %dx%d, tsize = %d, base = %dx%d", + // this.mapW, this.mapH, this.textureSize, w, h); + + this.baseW = w; + this.baseH = h; + + this.updateZoom(); + } + + public int getPixelsPerBlock() + { + return this.mapW / this.baseW; + } + + public boolean isBlockWithinView(double bX, double bZ, boolean circular) + { + boolean inside; + if (!circular) + { + inside = (bX > this.getMinX()) || (bX < this.getMaxX()) || (bZ > this.getMinZ()) || (bZ < this.getMaxZ()); + } + else + { + double x = (bX - this.x); + double z = (bZ - this.z); + double r = this.getHeight() / 2; + inside = ((x * x) + (z * z)) < (r * r); + } + return inside; + } + + public boolean getUndergroundMode() + { + return this.undergroundMode; + } + + public void setUndergroundMode(boolean enabled) + { + if (enabled) + { + if (this.zoomLevel >= 0) + { + this.setZoomLevel(-1); + } + } + this.undergroundMode = enabled; + } +} diff --git a/src/main/java/mapwriter/map/MapViewRequest.java b/src/main/java/mapwriter/map/MapViewRequest.java index 4c0b777d..27f4d016 100644 --- a/src/main/java/mapwriter/map/MapViewRequest.java +++ b/src/main/java/mapwriter/map/MapViewRequest.java @@ -2,10 +2,12 @@ import mapwriter.region.Region; -public class MapViewRequest { +public class MapViewRequest +{ public final int xMin, xMax, zMin, zMax, zoomLevel, dimension; - - public MapViewRequest(MapView view) { + + public MapViewRequest(MapView view) + { this.zoomLevel = view.getRegionZoomLevel(); int size = Region.SIZE << this.zoomLevel; this.xMin = ((int) view.getMinX()) & (-size); @@ -14,20 +16,14 @@ public MapViewRequest(MapView view) { this.zMax = ((int) view.getMaxZ()) & (-size); this.dimension = view.getDimension(); } - - public boolean equals(MapViewRequest req) { - return (req != null) && - (req.zoomLevel == this.zoomLevel) && - (req.dimension == this.dimension) && - (req.xMin == this.xMin) && - (req.xMax == this.xMax) && - (req.zMin == this.zMin) && - (req.zMax == this.zMax); + + public boolean equals(MapViewRequest req) + { + return (req != null) && (req.zoomLevel == this.zoomLevel) && (req.dimension == this.dimension) && (req.xMin == this.xMin) && (req.xMax == this.xMax) && (req.zMin == this.zMin) && (req.zMax == this.zMax); } - - public boolean mostlyEquals(MapViewRequest req) { - return (req != null) && - (req.zoomLevel == this.zoomLevel) && - (req.dimension == this.dimension); + + public boolean mostlyEquals(MapViewRequest req) + { + return (req != null) && (req.zoomLevel == this.zoomLevel) && (req.dimension == this.dimension); } } diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index d900bf71..7a03a64a 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -2,13 +2,14 @@ import java.awt.Point; -import net.minecraft.entity.Entity; -import net.minecraft.util.MathHelper; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Render; import mapwriter.util.Utils; +import net.minecraft.entity.Entity; +import net.minecraft.util.MathHelper; -public class Marker { +public class Marker +{ public final String name; public final String groupName; public int x; @@ -16,10 +17,11 @@ public class Marker { public int z; public int dimension; public int colour; - + public Point.Double screenPos = new Point.Double(0, 0); - - public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + + public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) + { this.name = name; this.x = x; this.y = y; @@ -28,53 +30,59 @@ public Marker(String name, String groupName, int x, int y, int z, int dimension, this.colour = colour; this.groupName = groupName; } - - public String getString() { - return String.format("%s %s (%d, %d, %d) %d %06x", - this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); + + public String getString() + { + return String.format("%s %s (%d, %d, %d) %d %06x", this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); } - - public void colourNext() - { + + public void colourNext() + { this.colour = Utils.getNextColour(); - } - - public void colourPrev() - { + } + + public void colourPrev() + { this.colour = Utils.getPrevColour(); - } - - public void draw(MapMode mapMode, MapView mapView, int borderColour) { + } + + public void draw(MapMode mapMode, MapView mapView, int borderColour) + { double scale = mapView.getDimensionScaling(this.dimension); Point.Double p = mapMode.getClampedScreenXY(mapView, this.x * scale, this.z * scale); this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); - + // draw a coloured rectangle centered on the calculated (x, y) double mSize = mapMode.config.markerSize; double halfMSize = mapMode.config.markerSize / 2.0; Render.setColour(borderColour); Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); Render.setColour(this.colour); - Render.drawRect(p.x - halfMSize + 0.5, p.y - halfMSize + 0.5, mSize - 1.0, mSize - 1.0); + Render.drawRect((p.x - halfMSize) + 0.5, (p.y - halfMSize) + 0.5, mSize - 1.0, mSize - 1.0); } // arraylist.contains was producing unexpected results in some situations // rather than figure out why i'll just control how two markers are compared @Override - public boolean equals(final Object o) { - if (this == o) { return true; } - if (o instanceof Marker) { + public boolean equals(final Object o) + { + if (this == o) + { + return true; + } + if (o instanceof Marker) + { Marker m = (Marker) o; - return (name == m.name) && (groupName == m.groupName) && (x == m.x) && (y == m.y) && (z == m.z) && (dimension == m.dimension); + return (this.name == m.name) && (this.groupName == m.groupName) && (this.x == m.x) && (this.y == m.y) && (this.z == m.z) && (this.dimension == m.dimension); } return false; } - - public double getDistanceToMarker(Entity entityIn) - { - double d0 = this.x - entityIn.posX; - double d1 = this.y - entityIn.posY; - double d2 = this.z - entityIn.posZ; - return (double)MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); - } + + public double getDistanceToMarker(Entity entityIn) + { + double d0 = this.x - entityIn.posX; + double d1 = this.y - entityIn.posY; + double d2 = this.z - entityIn.posZ; + return MathHelper.sqrt_double((d0 * d0) + (d1 * d1) + (d2 * d2)); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index 3c724713..39c24273 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -1,5 +1,7 @@ package mapwriter.map; +import static org.lwjgl.opengl.ARBDepthClamp.GL_DEPTH_CLAMP; + import java.util.ArrayList; import java.util.List; @@ -9,7 +11,6 @@ import mapwriter.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; @@ -18,143 +19,166 @@ import net.minecraftforge.common.config.Configuration; import org.lwjgl.opengl.GL11; -import static org.lwjgl.opengl.ARBDepthClamp.GL_DEPTH_CLAMP; -public class MarkerManager { - +public class MarkerManager +{ + public List markerList = new ArrayList(); public List groupList = new ArrayList(); - + public List visibleMarkerList = new ArrayList(); - + private String visibleGroupName = "none"; - + public Marker selectedMarker = null; - - public MarkerManager() { + + public MarkerManager() + { } - - public void load(Configuration config, String category) { + + public void load(Configuration config, String category) + { this.markerList.clear(); - - if (config.hasCategory(category)) { + + if (config.hasCategory(category)) + { int markerCount = config.get(category, "markerCount", 0).getInt(); this.visibleGroupName = config.get(category, "visibleGroup", "").getString(); - - if (markerCount > 0) { - for (int i = 0; i < markerCount; i++) { + + if (markerCount > 0) + { + for (int i = 0; i < markerCount; i++) + { String key = "marker" + i; String value = config.get(category, key, "").getString(); Marker marker = this.stringToMarker(value); - if (marker != null) { + if (marker != null) + { this.addMarker(marker); - } else { + } + else + { Logging.log("error: could not load " + key + " from config file"); } } } } - + this.update(); } - - public void save(Configuration config, String category) { + + public void save(Configuration config, String category) + { config.get(category, "markerCount", 0).set(this.markerList.size()); config.get(category, "visibleGroup", "").set(this.visibleGroupName); - + int i = 0; - for (Marker marker : this.markerList) { + for (Marker marker : this.markerList) + { String key = "marker" + i; String value = this.markerToString(marker); config.get(category, key, "").set(value); i++; } } - - public void setVisibleGroupName(String groupName) { - if (groupName != null) { + + public void setVisibleGroupName(String groupName) + { + if (groupName != null) + { this.visibleGroupName = Utils.mungeString(groupName); - } else { + } + else + { this.visibleGroupName = "none"; } } - - public String getVisibleGroupName() { + + public String getVisibleGroupName() + { return this.visibleGroupName; } - - public void clear() { + + public void clear() + { this.markerList.clear(); this.groupList.clear(); this.visibleMarkerList.clear(); this.visibleGroupName = "none"; } - - public String markerToString(Marker marker) { - return String.format("%s:%d:%d:%d:%d:%06x:%s", - marker.name, - marker.x, marker.y, marker.z, - marker.dimension, - marker.colour & 0xffffff, - marker.groupName - ); + + public String markerToString(Marker marker) + { + return String.format("%s:%d:%d:%d:%d:%06x:%s", marker.name, marker.x, marker.y, marker.z, marker.dimension, marker.colour & 0xffffff, marker.groupName); } - - public Marker stringToMarker(String s) { + + public Marker stringToMarker(String s) + { // new style delimited with colons String[] split = s.split(":"); - if (split.length != 7) { + if (split.length != 7) + { // old style was space delimited split = s.split(" "); } Marker marker = null; - if (split.length == 7) { - try { + if (split.length == 7) + { + try + { int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); int dimension = Integer.parseInt(split[4]); int colour = 0xff000000 | Integer.parseInt(split[5], 16); - + marker = new Marker(split[0], split[6], x, y, z, dimension, colour); - - } catch (NumberFormatException e) { + + } + catch (NumberFormatException e) + { marker = null; } - } else { + } + else + { Logging.log("Marker.stringToMarker: invalid marker '%s'", s); } return marker; } - - public void addMarker(Marker marker) { + + public void addMarker(Marker marker) + { this.markerList.add(marker); } - - public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + + public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) + { name = name.replace(":", ""); groupName = groupName.replace(":", ""); this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); } - + // returns true if the marker exists in the arraylist. // safe to pass null. - public boolean delMarker(Marker markerToDelete) + public boolean delMarker(Marker markerToDelete) { if (this.selectedMarker == markerToDelete) { - selectedMarker = null; + this.selectedMarker = null; } return this.markerList.remove(markerToDelete); } - + // deletes the first marker with matching name and group. // if null is passed as either name or group it means "any". - public boolean delMarker(String name, String group) { + public boolean delMarker(String name, String group) + { Marker markerToDelete = null; - for (Marker marker : this.markerList) { - if (((name == null) || marker.name.equals(name)) && - ((group == null) || marker.groupName.equals(group))) { + for (Marker marker : this.markerList) + { + if (((name == null) || marker.name.equals(name)) && ((group == null) || marker.groupName.equals(group))) + { markerToDelete = marker; break; } @@ -163,110 +187,133 @@ public boolean delMarker(String name, String group) { // (i.e. if markerToDelete is null) return this.delMarker(markerToDelete); } - - /*public boolean delGroup(String groupName) { - boolean error = !this.groupList.remove(groupName); - Iterator it = this.markerMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - Marker marker = (Marker) entry.getValue(); - if (marker.groupName.equals(groupName)) { - it.remove(); - } - } - if (groupName == this.visibleGroupName) { - this.nextGroup(); - } - return error; - }*/ - - public void update() { + + /* + * public boolean delGroup(String groupName) { boolean error = + * !this.groupList.remove(groupName); Iterator it = + * this.markerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry + * entry = (Map.Entry) it.next(); Marker marker = (Marker) entry.getValue(); + * if (marker.groupName.equals(groupName)) { it.remove(); } } if (groupName + * == this.visibleGroupName) { this.nextGroup(); } return error; } + */ + + public void update() + { this.visibleMarkerList.clear(); this.groupList.clear(); this.groupList.add("none"); this.groupList.add("all"); - for (Marker marker : this.markerList) { - if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) { + for (Marker marker : this.markerList) + { + if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) + { this.visibleMarkerList.add(marker); } - if (!this.groupList.contains(marker.groupName)) { + if (!this.groupList.contains(marker.groupName)) + { this.groupList.add(marker.groupName); } } - if (!this.groupList.contains(this.visibleGroupName)) { + if (!this.groupList.contains(this.visibleGroupName)) + { this.visibleGroupName = "none"; } } - - public void nextGroup(int n) { - if (this.groupList.size() > 0) { + + public void nextGroup(int n) + { + if (this.groupList.size() > 0) + { int i = this.groupList.indexOf(this.visibleGroupName); int size = this.groupList.size(); - if (i != -1) { + if (i != -1) + { i = (i + size + n) % size; - } else { + } + else + { i = 0; } this.visibleGroupName = this.groupList.get(i); - } else { + } + else + { this.visibleGroupName = "none"; this.groupList.add("none"); } } - - public void nextGroup() { + + public void nextGroup() + { this.nextGroup(1); } - - public int countMarkersInGroup(String group) { + + public int countMarkersInGroup(String group) + { int count = 0; - if (group.equals("all")) { + if (group.equals("all")) + { count = this.markerList.size(); - } else { - for (Marker marker : this.markerList) { - if (marker.groupName.equals(group)) { + } + else + { + for (Marker marker : this.markerList) + { + if (marker.groupName.equals(group)) + { count++; } } } return count; } - - public void selectNextMarker() { - if (this.visibleMarkerList.size() > 0) { - int i = 0; - if (this.selectedMarker != null) { - i = this.visibleMarkerList.indexOf(this.selectedMarker); - if (i == -1) { - i = 0; - } - } - i = (i + 1) % this.visibleMarkerList.size(); - this.selectedMarker = this.visibleMarkerList.get(i); - } else { - this.selectedMarker = null; - } + + public void selectNextMarker() + { + if (this.visibleMarkerList.size() > 0) + { + int i = 0; + if (this.selectedMarker != null) + { + i = this.visibleMarkerList.indexOf(this.selectedMarker); + if (i == -1) + { + i = 0; + } + } + i = (i + 1) % this.visibleMarkerList.size(); + this.selectedMarker = this.visibleMarkerList.get(i); + } + else + { + this.selectedMarker = null; + } } - - public Marker getNearestMarker(int x, int z, int maxDistance) { + + public Marker getNearestMarker(int x, int z, int maxDistance) + { int nearestDistance = maxDistance * maxDistance; Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { + for (Marker marker : this.visibleMarkerList) + { int dx = x - marker.x; int dz = z - marker.z; int d = (dx * dx) + (dz * dz); - if (d < nearestDistance) { + if (d < nearestDistance) + { nearestMarker = marker; nearestDistance = d; } } return nearestMarker; } - - public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { + + public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) + { int nearestDistance = 10000 * 10000; Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { + for (Marker marker : this.visibleMarkerList) + { int dx = marker.x - x; int dz = marker.z - z; int d = (dx * dx) + (dz * dz); @@ -275,22 +322,27 @@ public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { // cos will be closer to 1.0 the closer desiredAngle and angle are. // 0.8 is the threshold corresponding to a maximum of // acos(0.8) = 37 degrees difference between the two angles. - if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) { + if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) + { nearestMarker = marker; nearestDistance = d; } } return nearestMarker; } - - public void drawMarkers(MapMode mapMode, MapView mapView) { - for (Marker marker : this.visibleMarkerList) { - // only draw markers that were set in the current dimension - if (mapView.getDimension() == marker.dimension) { + + public void drawMarkers(MapMode mapMode, MapView mapView) + { + for (Marker marker : this.visibleMarkerList) + { + // only draw markers that were set in the current dimension + if (mapView.getDimension() == marker.dimension) + { marker.draw(mapMode, mapView, 0xff000000); } } - if (this.selectedMarker != null) { + if (this.selectedMarker != null) + { this.selectedMarker.draw(mapMode, mapView, 0xffffffff); } } @@ -308,11 +360,11 @@ public void drawMarkersWorld(float partialTicks) { if (Config.drawMarkersInWorld) { - drawBeam(m, partialTicks); + this.drawBeam(m, partialTicks); } if (Config.drawMarkersNameInWorld) { - drawLabel(m); + this.drawLabel(m); } } } @@ -323,14 +375,14 @@ public void drawBeam(Marker m, float partialTicks) Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - float f2 = (float) Minecraft.getMinecraft().theWorld.getTotalWorldTime() + partialTicks; - double d3 = (double) f2 * 0.025D * -1.5D; + float f2 = Minecraft.getMinecraft().theWorld.getTotalWorldTime() + partialTicks; + double d3 = f2 * 0.025D * -1.5D; // the height of the beam always to the max height double d17 = 255.0D; - double x = (double) m.x - TileEntityRendererDispatcher.staticPlayerX; + double x = m.x - TileEntityRendererDispatcher.staticPlayerX; double y = 0.0D - TileEntityRendererDispatcher.staticPlayerY; - double z = (double) m.z - TileEntityRendererDispatcher.staticPlayerZ; + double z = m.z - TileEntityRendererDispatcher.staticPlayerZ; GlStateManager.pushMatrix(); GlStateManager.disableTexture2D(); @@ -344,14 +396,14 @@ public void drawBeam(Marker m, float partialTicks) // size of the square from middle to edge double d4 = 0.2D; - double d5 = 0.5D + Math.cos(d3 + 2.356194490192345D) * d4; - double d6 = 0.5D + Math.sin(d3 + 2.356194490192345D) * d4; - double d7 = 0.5D + Math.cos(d3 + (Math.PI / 4D)) * d4; - double d8 = 0.5D + Math.sin(d3 + (Math.PI / 4D)) * d4; - double d9 = 0.5D + Math.cos(d3 + 3.9269908169872414D) * d4; - double d10 = 0.5D + Math.sin(d3 + 3.9269908169872414D) * d4; - double d11 = 0.5D + Math.cos(d3 + 5.497787143782138D) * d4; - double d12 = 0.5D + Math.sin(d3 + 5.497787143782138D) * d4; + double d5 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); + double d6 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); + double d7 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); + double d8 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); + double d9 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); + double d10 = 0.5D + (Math.sin(d3 + 3.9269908169872414D) * d4); + double d11 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); + double d12 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); worldrenderer.setColorRGBA_I(m.colour, 50); @@ -378,14 +430,14 @@ public void drawBeam(Marker m, float partialTicks) // size of the square from middle to edge d4 = 0.5D; - d5 = 0.5D + Math.sin(d3 + 2.356194490192345D) * d4; - d6 = 0.5D + Math.cos(d3 + 2.356194490192345D) * d4; - d7 = 0.5D + Math.sin(d3 + (Math.PI / 4D)) * d4; - d8 = 0.5D + Math.cos(d3 + (Math.PI / 4D)) * d4; - d9 = 0.5D + Math.sin(d3 + 3.9269908169872414D) * d4; - d10 = 0.5D + Math.cos(d3 + 3.9269908169872414D) * d4; - d11 = 0.5D + Math.sin(d3 + 5.497787143782138D) * d4; - d12 = 0.5D + Math.cos(d3 + 5.497787143782138D) * d4; + d5 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); + d6 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); + d7 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); + d8 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); + d9 = 0.5D + (Math.sin(d3 + 3.9269908169872414D) * d4); + d10 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); + d11 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); + d12 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); worldrenderer.addVertex(x + d5, y + d17, z + d6); worldrenderer.addVertex(x + d5, y, z + d6); @@ -411,28 +463,28 @@ public void drawBeam(Marker m, float partialTicks) GlStateManager.disableBlend(); GlStateManager.popMatrix(); } - + public void drawLabel(Marker m) { - float growFactor = 0.17F; + float growFactor = 0.17F; Minecraft mc = Minecraft.getMinecraft(); RenderManager renderManager = mc.getRenderManager(); FontRenderer fontrenderer = mc.fontRendererObj; - double x = 0.5D + (double) m.x - TileEntityRendererDispatcher.staticPlayerX; - double y = 0.5D + (double) m.y - TileEntityRendererDispatcher.staticPlayerY; - double z = 0.5D + (double) m.z - TileEntityRendererDispatcher.staticPlayerZ; - + double x = (0.5D + m.x) - TileEntityRendererDispatcher.staticPlayerX; + double y = (0.5D + m.y) - TileEntityRendererDispatcher.staticPlayerY; + double z = (0.5D + m.z) - TileEntityRendererDispatcher.staticPlayerZ; + double distance = m.getDistanceToMarker(renderManager.livingPlayer); - + String strText = m.name; - String strDistance = " (" + (int)distance + "m)"; - + String strDistance = " (" + (int) distance + "m)"; + int strTextWidth = fontrenderer.getStringWidth(strText) / 2; int strDistanceWidth = fontrenderer.getStringWidth(strDistance) / 2; int offstet = 9; - - float f = (float) (1.0F + (distance)*growFactor); + + float f = (float) (1.0F + ((distance) * growFactor)); float f1 = 0.016666668F * f; GlStateManager.pushMatrix(); @@ -447,7 +499,7 @@ public void drawLabel(Marker m) GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GL11.glEnable(GL_DEPTH_CLAMP); - + Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); @@ -455,18 +507,18 @@ public void drawLabel(Marker m) worldrenderer.startDrawingQuads(); worldrenderer.setColorRGBA_I(m.colour, 64); - worldrenderer.addVertex((double) (-strTextWidth - 1), (double) (-1), 0.0D); - worldrenderer.addVertex((double) (-strTextWidth - 1), (double) (8), 0.0D); - worldrenderer.addVertex((double) (strTextWidth + 1), (double) (8), 0.0D); - worldrenderer.addVertex((double) (strTextWidth + 1), (double) (-1), 0.0D); + worldrenderer.addVertex(-strTextWidth - 1, (-1), 0.0D); + worldrenderer.addVertex(-strTextWidth - 1, (8), 0.0D); + worldrenderer.addVertex(strTextWidth + 1, (8), 0.0D); + worldrenderer.addVertex(strTextWidth + 1, (-1), 0.0D); tessellator.draw(); - + worldrenderer.startDrawingQuads(); worldrenderer.setColorRGBA_I(m.colour, 64); - worldrenderer.addVertex((double) (-strDistanceWidth - 1), (double) (-1 + offstet), 0.0D); - worldrenderer.addVertex((double) (-strDistanceWidth - 1), (double) (8 + offstet), 0.0D); - worldrenderer.addVertex((double) (strDistanceWidth + 1), (double) (8 + offstet), 0.0D); - worldrenderer.addVertex((double) (strDistanceWidth + 1), (double) (-1 + offstet), 0.0D); + worldrenderer.addVertex(-strDistanceWidth - 1, -1 + offstet, 0.0D); + worldrenderer.addVertex(-strDistanceWidth - 1, 8 + offstet, 0.0D); + worldrenderer.addVertex(strDistanceWidth + 1, 8 + offstet, 0.0D); + worldrenderer.addVertex(strDistanceWidth + 1, -1 + offstet, 0.0D); tessellator.draw(); GlStateManager.enableTexture2D(); diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java index 3ae3a0e2..e8c78bf3 100644 --- a/src/main/java/mapwriter/map/MiniMap.java +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -1,81 +1,89 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.config.Config; -import mapwriter.map.mapmode.LargeMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.map.mapmode.SmallMapMode; - -public class MiniMap { - public MapMode smallMapMode; - public MapMode largeMapMode; - public MapMode guiMapMode; - - public MapView view; - - public MapRenderer smallMap; - public MapRenderer largeMap; - - private List mapList; - private MapRenderer currentMap = null; - - public MiniMap(Mw mw) { - // map view shared between large and small map modes - this.view = new MapView(mw, false); - this.view.setZoomLevel(Config.overlayZoomLevel); - - // small map mode - this.smallMapMode = new SmallMapMode(); - this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); - - // large map mode - this.largeMapMode = new LargeMapMode(); - this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); - - this.mapList = new ArrayList(); - - // add small, large and underground map modes if they - // are enabled. - if (this.smallMapMode.config.enabled) { - this.mapList.add(this.smallMap); - } - if (this.largeMapMode.config.enabled) { - this.mapList.add(this.largeMap); - } - // add a null entry (hides the overlay when selected) - this.mapList.add(null); - - // sanitize overlayModeIndex loaded from config - this.nextOverlayMode(0); - this.currentMap = this.mapList.get(Config.overlayModeIndex); - } - - public void close() { - this.mapList.clear(); - this.currentMap = null; - } - - // toggle between small map, underground map and no map - public MapRenderer nextOverlayMode(int increment) { - int size = this.mapList.size(); - Config.overlayModeIndex = (Config.overlayModeIndex + size + increment) % size; - - MapRenderer newMap = this.mapList.get(Config.overlayModeIndex); - - //if (newMap.getMapMode().config.enabled) - //{ - this.currentMap = newMap; - //} - return this.currentMap; - } - - // draw the map overlay, player arrow, and markers - public void drawCurrentMap() { - if (this.currentMap != null) { - this.currentMap.draw(); - } - } +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.config.Config; +import mapwriter.map.mapmode.LargeMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.map.mapmode.SmallMapMode; + +public class MiniMap +{ + public MapMode smallMapMode; + public MapMode largeMapMode; + public MapMode guiMapMode; + + public MapView view; + + public MapRenderer smallMap; + public MapRenderer largeMap; + + private List mapList; + private MapRenderer currentMap = null; + + public MiniMap(Mw mw) + { + // map view shared between large and small map modes + this.view = new MapView(mw, false); + this.view.setZoomLevel(Config.overlayZoomLevel); + + // small map mode + this.smallMapMode = new SmallMapMode(); + this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); + + // large map mode + this.largeMapMode = new LargeMapMode(); + this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); + + this.mapList = new ArrayList(); + + // add small, large and underground map modes if they + // are enabled. + if (this.smallMapMode.config.enabled) + { + this.mapList.add(this.smallMap); + } + if (this.largeMapMode.config.enabled) + { + this.mapList.add(this.largeMap); + } + // add a null entry (hides the overlay when selected) + this.mapList.add(null); + + // sanitize overlayModeIndex loaded from config + this.nextOverlayMode(0); + this.currentMap = this.mapList.get(Config.overlayModeIndex); + } + + public void close() + { + this.mapList.clear(); + this.currentMap = null; + } + + // toggle between small map, underground map and no map + public MapRenderer nextOverlayMode(int increment) + { + int size = this.mapList.size(); + Config.overlayModeIndex = (Config.overlayModeIndex + size + increment) % size; + + MapRenderer newMap = this.mapList.get(Config.overlayModeIndex); + + // if (newMap.getMapMode().config.enabled) + // { + this.currentMap = newMap; + // } + return this.currentMap; + } + + // draw the map overlay, player arrow, and markers + public void drawCurrentMap() + { + if (this.currentMap != null) + { + this.currentMap.draw(); + } + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java index 39fd55f5..e55994b0 100644 --- a/src/main/java/mapwriter/map/Trail.java +++ b/src/main/java/mapwriter/map/Trail.java @@ -9,32 +9,38 @@ import mapwriter.util.Reference; import mapwriter.util.Render; -public class Trail { - - class TrailMarker { - +public class Trail +{ + + class TrailMarker + { + double x, y, z, heading; int alphaPercent; - + static final int borderColour = 0xff000000; static final int colour = 0xff00ffff; - - public TrailMarker(double x, double y, double z, double heading) { + + public TrailMarker(double x, double y, double z, double heading) + { this.set(x, y, z, heading); } - - public void set(double x, double y, double z, double heading) { + + public void set(double x, double y, double z, double heading) + { this.x = x; this.y = y; this.z = z; this.heading = heading; this.alphaPercent = 100; } - - public void draw(MapMode mapMode, MapView mapView) { - if (mapView.isBlockWithinView(this.x, this.z, mapMode.config.circular)) { + + public void draw(MapMode mapMode, MapView mapView) + { + if (mapView.isBlockWithinView(this.x, this.z, mapMode.config.circular)) + { Point.Double p = mapMode.blockXZtoScreenXY(mapView, this.x, this.z); - + // draw a coloured arrow centered on the calculated (x, y) Render.setColourWithAlphaPercent(borderColour, this.alphaPercent); Render.drawArrow(p.x, p.y, this.heading, mapMode.config.trailMarkerSize); @@ -43,7 +49,7 @@ public void draw(MapMode mapMode, MapView mapView) { } } } - + private Mw mw; public LinkedList trailMarkerList = new LinkedList(); public int maxLength = 30; @@ -51,50 +57,62 @@ public void draw(MapMode mapMode, MapView mapView) { public boolean enabled; public long lastMarkerTime = 0; public long intervalMillis = 5000; - - public Trail(Mw mw, String name) { + + public Trail(Mw mw, String name) + { this.mw = mw; this.name = name; this.enabled = ConfigurationHandler.configuration.getBoolean(this.name + "TrailEnabled", Reference.catOptions, false, ""); this.maxLength = ConfigurationHandler.configuration.getInt(this.name + "TrailMaxLength", Reference.catOptions, this.maxLength, 1, 200, ""); - this.intervalMillis = (long) ConfigurationHandler.configuration.getInt(this.name + "TrailMarkerIntervalMillis", Reference.catOptions, (int) this.intervalMillis, 100, 360000, ""); + this.intervalMillis = ConfigurationHandler.configuration.getInt(this.name + "TrailMarkerIntervalMillis", Reference.catOptions, (int) this.intervalMillis, 100, 360000, ""); } - - public void close() { - //this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); - //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); - //this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); + + public void close() + { + // this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", + // this.enabled); + // this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", + // this.maxLength); + // this.mw.config.setInt(Mw.catOptions, this.name + + // "TrailMarkerIntervalMillis", (int) this.intervalMillis); this.trailMarkerList.clear(); } - - // for other types of trails will need to extend Trail and override this method - public void onTick() { + + // for other types of trails will need to extend Trail and override this + // method + public void onTick() + { long time = System.currentTimeMillis(); - if ((time - this.lastMarkerTime) > this.intervalMillis) { - this.lastMarkerTime = time; - this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); - } + if ((time - this.lastMarkerTime) > this.intervalMillis) + { + this.lastMarkerTime = time; + this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); + } } - - public void addMarker(double x, double y, double z, double heading) { + + public void addMarker(double x, double y, double z, double heading) + { this.trailMarkerList.add(new TrailMarker(x, y, z, heading)); // remove elements from beginning of list until the list has at most // maxTrailLength elements - while (this.trailMarkerList.size() > this.maxLength) { + while (this.trailMarkerList.size() > this.maxLength) + { this.trailMarkerList.poll(); } int i = this.maxLength - this.trailMarkerList.size(); - for (TrailMarker marker : this.trailMarkerList) { + for (TrailMarker marker : this.trailMarkerList) + { marker.alphaPercent = (i * 100) / this.maxLength; i++; } } - - public void draw(MapMode mapMode, MapView mapView) { - for (TrailMarker marker : this.trailMarkerList) { + + public void draw(MapMode mapMode, MapView mapView) + { + for (TrailMarker marker : this.trailMarkerList) + { marker.draw(mapMode, mapView); } } - - + } diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java index 23845680..797e9015 100644 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -1,221 +1,246 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.Arrays; - -import mapwriter.Mw; -import mapwriter.region.ChunkRender; -import mapwriter.region.IChunk; -import mapwriter.util.Texture; -import net.minecraft.block.Block; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.util.BlockPos; -import net.minecraft.world.chunk.Chunk; - -import org.lwjgl.opengl.GL11; - -public class UndergroundTexture extends Texture { - - private Mw mw; - private int px = 0; - private int py = 0; - private int pz = 0; - private int dimension = 0; - private int updateX; - private int updateZ; - private byte[][] updateFlags = new byte[9][256]; - private Point[] loadedChunkArray; - private int textureSize; - private int textureChunks; - private int[] pixels; - - class RenderChunk implements IChunk { - Chunk chunk; - - public RenderChunk(Chunk chunk) { - this.chunk = chunk; - } - - @Override - public int getMaxY() { - return this.chunk.getTopFilledSegment() + 15; - } - - @Override - public int getBlockAndMetadata(int x, int y, int z) { - Block block = this.chunk.getBlock(x, y, z); - int blockid = Block.blockRegistry.getIDForObject(block); - int meta = this.chunk.getBlockMetadata(new BlockPos(x, y, z)); - return ((blockid & 0xfff) << 4) | (meta & 0xf); - } - - @Override - public int getBiome(int x, int z) { - return (int) this.chunk.getBiomeArray()[(z * 16) + x]; - } - - @Override - public int getLightValue(int x, int y, int z) { - return this.chunk.getLightSubtracted(new BlockPos(x,y,z),0); - } - } - - public UndergroundTexture(Mw mw, int textureSize, boolean linearScaling) { - super(textureSize, textureSize, 0x00000000, GL11.GL_NEAREST, GL11.GL_NEAREST, GL11.GL_REPEAT); - this.setLinearScaling(false); - this.textureSize = textureSize; - this.textureChunks = textureSize >> 4; - this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; - this.pixels = new int[textureSize * textureSize]; - Arrays.fill(this.pixels, 0xff000000); - this.mw = mw; - } - - public void clear() { - Arrays.fill(this.pixels, 0xff000000); - this.updateTexture(); - } - - public void clearChunkPixels(int cx, int cz) { - int tx = (cx << 4) & (this.textureSize - 1); - int tz = (cz << 4) & (this.textureSize - 1); - for (int j = 0; j < 16; j++) { - int offset = ((tz + j) * this.textureSize) + tx; - Arrays.fill(this.pixels, offset, offset + 16, 0xff000000); - } - this.updateTextureArea(tx, tz, 16, 16); - } - - void renderToTexture(int y) { - this.setPixelBufPosition(0); - for (int i = 0; i < this.pixels.length; i++) { - int colour = this.pixels[i]; - int height = (colour >> 24) & 0xff; - int alpha = (y >= height) ? 255 - ((y - height) * 8) : 0; - if (alpha < 0) { - alpha = 0; - } - this.pixelBufPut(((alpha << 24) & 0xff000000) | (colour & 0xffffff)); - } - this.updateTexture(); - } - - public int getLoadedChunkOffset(int cx, int cz) { - int cxOffset = cx & (this.textureChunks - 1); - int czOffset = cz & (this.textureChunks - 1); - return (czOffset * this.textureChunks) + cxOffset; - } - - public void requestView(MapView view) { - int cxMin = ((int) view.getMinX()) >> 4; - int czMin = ((int) view.getMinZ()) >> 4; - int cxMax = ((int) view.getMaxX()) >> 4; - int czMax = ((int) view.getMaxZ()) >> 4; - for (int cz = czMin; cz <= czMax; cz++) { - for (int cx = cxMin; cx <= cxMax; cx++) { - Point requestedChunk = new Point(cx, cz); - int offset = this.getLoadedChunkOffset(cx, cz); - Point currentChunk = this.loadedChunkArray[offset]; - if ((currentChunk == null) || !currentChunk.equals(requestedChunk)) { - this.clearChunkPixels(cx, cz); - this.loadedChunkArray[offset] = requestedChunk; - } - } - } - } - - public boolean isChunkInTexture(int cx, int cz) { - Point requestedChunk = new Point(cx, cz); - int offset = this.getLoadedChunkOffset(cx, cz); - Point chunk = this.loadedChunkArray[offset]; - return (chunk != null) && chunk.equals(requestedChunk); - } - - public void update() { - this.clearFlags(); - - if (this.dimension != this.mw.playerDimension) { - this.clear(); - this.dimension = this.mw.playerDimension; - } - this.px = this.mw.playerXInt; - this.py = this.mw.playerYInt; - this.pz = this.mw.playerZInt; - - this.updateX = (this.px >> 4) - 1; - this.updateZ = (this.pz >> 4) - 1; - - this.processBlock( - this.px - (this.updateX << 4), - this.py, - this.pz - (this.updateZ << 4) - ); - - int cxMax = this.updateX + 2; - int czMax = this.updateZ + 2; - WorldClient world = this.mw.mc.theWorld; - int flagOffset = 0; - for (int cz = this.updateZ; cz <= czMax; cz++) { - for (int cx = this.updateX; cx <= cxMax; cx++) { - if (this.isChunkInTexture(cx, cz)) { - Chunk chunk = world.getChunkFromChunkCoords(cx, cz); - int tx = (cx << 4) & (this.textureSize - 1); - int tz = (cz << 4) & (this.textureSize - 1); - int pixelOffset = (tz * this.textureSize) + tx; - byte[] mask = this.updateFlags[flagOffset]; - ChunkRender.renderUnderground( - this.mw.blockColours, - new RenderChunk(chunk), - this.pixels, pixelOffset, this.textureSize, - this.py, mask - ); - } - flagOffset += 1; - } - } - - this.renderToTexture(this.py + 1); - } - - private void clearFlags() { - for (byte[] chunkFlags : this.updateFlags) { - Arrays.fill(chunkFlags, ChunkRender.FLAG_UNPROCESSED); - } - } - - private void processBlock(int xi, int y, int zi) { - int x = (this.updateX << 4) + xi; - int z = (this.updateZ << 4) + zi; - - int xDist = this.px - x; - int zDist = this.pz - z; - - if (((xDist * xDist) + (zDist * zDist)) <= 256) { - if (this.isChunkInTexture(x >> 4, z >> 4)) { - int chunkOffset = ((zi >> 4) * 3) + (xi >> 4); - int columnXi = xi & 0xf; - int columnZi = zi & 0xf; - int columnOffset = (columnZi << 4) + columnXi; - byte columnFlag = this.updateFlags[chunkOffset][columnOffset]; - - if (columnFlag == ChunkRender.FLAG_UNPROCESSED) { - // if column not yet processed - WorldClient world = this.mw.mc.theWorld; - Block block = world.getBlockState(new BlockPos(x,y,z)).getBlock(); - if ((block == null) || !block.isOpaqueCube()) { - // if block is not opaque - this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_NON_OPAQUE; - this.processBlock(xi + 1, y, zi); - this.processBlock(xi - 1, y, zi); - this.processBlock(xi, y, zi + 1); - this.processBlock(xi, y, zi - 1); - } else { - // block is opaque - this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_OPAQUE; - } - } - } - } - } - -} +package mapwriter.map; + +import java.awt.Point; +import java.util.Arrays; + +import mapwriter.Mw; +import mapwriter.region.ChunkRender; +import mapwriter.region.IChunk; +import mapwriter.util.Texture; +import net.minecraft.block.Block; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.Chunk; + +import org.lwjgl.opengl.GL11; + +public class UndergroundTexture extends Texture +{ + + private Mw mw; + private int px = 0; + private int py = 0; + private int pz = 0; + private int dimension = 0; + private int updateX; + private int updateZ; + private byte[][] updateFlags = new byte[9][256]; + private Point[] loadedChunkArray; + private int textureSize; + private int textureChunks; + private int[] pixels; + + class RenderChunk implements IChunk + { + Chunk chunk; + + public RenderChunk(Chunk chunk) + { + this.chunk = chunk; + } + + @Override + public int getMaxY() + { + return this.chunk.getTopFilledSegment() + 15; + } + + @Override + public int getBlockAndMetadata(int x, int y, int z) + { + Block block = this.chunk.getBlock(x, y, z); + int blockid = Block.blockRegistry.getIDForObject(block); + int meta = this.chunk.getBlockMetadata(new BlockPos(x, y, z)); + return ((blockid & 0xfff) << 4) | (meta & 0xf); + } + + @Override + public int getBiome(int x, int z) + { + return this.chunk.getBiomeArray()[(z * 16) + x]; + } + + @Override + public int getLightValue(int x, int y, int z) + { + return this.chunk.getLightSubtracted(new BlockPos(x, y, z), 0); + } + } + + public UndergroundTexture(Mw mw, int textureSize, boolean linearScaling) + { + super(textureSize, textureSize, 0x00000000, GL11.GL_NEAREST, GL11.GL_NEAREST, GL11.GL_REPEAT); + this.setLinearScaling(false); + this.textureSize = textureSize; + this.textureChunks = textureSize >> 4; + this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; + this.pixels = new int[textureSize * textureSize]; + Arrays.fill(this.pixels, 0xff000000); + this.mw = mw; + } + + public void clear() + { + Arrays.fill(this.pixels, 0xff000000); + this.updateTexture(); + } + + public void clearChunkPixels(int cx, int cz) + { + int tx = (cx << 4) & (this.textureSize - 1); + int tz = (cz << 4) & (this.textureSize - 1); + for (int j = 0; j < 16; j++) + { + int offset = ((tz + j) * this.textureSize) + tx; + Arrays.fill(this.pixels, offset, offset + 16, 0xff000000); + } + this.updateTextureArea(tx, tz, 16, 16); + } + + void renderToTexture(int y) + { + this.setPixelBufPosition(0); + for (int i = 0; i < this.pixels.length; i++) + { + int colour = this.pixels[i]; + int height = (colour >> 24) & 0xff; + int alpha = (y >= height) ? 255 - ((y - height) * 8) : 0; + if (alpha < 0) + { + alpha = 0; + } + this.pixelBufPut(((alpha << 24) & 0xff000000) | (colour & 0xffffff)); + } + this.updateTexture(); + } + + public int getLoadedChunkOffset(int cx, int cz) + { + int cxOffset = cx & (this.textureChunks - 1); + int czOffset = cz & (this.textureChunks - 1); + return (czOffset * this.textureChunks) + cxOffset; + } + + public void requestView(MapView view) + { + int cxMin = ((int) view.getMinX()) >> 4; + int czMin = ((int) view.getMinZ()) >> 4; + int cxMax = ((int) view.getMaxX()) >> 4; + int czMax = ((int) view.getMaxZ()) >> 4; + for (int cz = czMin; cz <= czMax; cz++) + { + for (int cx = cxMin; cx <= cxMax; cx++) + { + Point requestedChunk = new Point(cx, cz); + int offset = this.getLoadedChunkOffset(cx, cz); + Point currentChunk = this.loadedChunkArray[offset]; + if ((currentChunk == null) || !currentChunk.equals(requestedChunk)) + { + this.clearChunkPixels(cx, cz); + this.loadedChunkArray[offset] = requestedChunk; + } + } + } + } + + public boolean isChunkInTexture(int cx, int cz) + { + Point requestedChunk = new Point(cx, cz); + int offset = this.getLoadedChunkOffset(cx, cz); + Point chunk = this.loadedChunkArray[offset]; + return (chunk != null) && chunk.equals(requestedChunk); + } + + public void update() + { + this.clearFlags(); + + if (this.dimension != this.mw.playerDimension) + { + this.clear(); + this.dimension = this.mw.playerDimension; + } + this.px = this.mw.playerXInt; + this.py = this.mw.playerYInt; + this.pz = this.mw.playerZInt; + + this.updateX = (this.px >> 4) - 1; + this.updateZ = (this.pz >> 4) - 1; + + this.processBlock(this.px - (this.updateX << 4), this.py, this.pz - (this.updateZ << 4)); + + int cxMax = this.updateX + 2; + int czMax = this.updateZ + 2; + WorldClient world = this.mw.mc.theWorld; + int flagOffset = 0; + for (int cz = this.updateZ; cz <= czMax; cz++) + { + for (int cx = this.updateX; cx <= cxMax; cx++) + { + if (this.isChunkInTexture(cx, cz)) + { + Chunk chunk = world.getChunkFromChunkCoords(cx, cz); + int tx = (cx << 4) & (this.textureSize - 1); + int tz = (cz << 4) & (this.textureSize - 1); + int pixelOffset = (tz * this.textureSize) + tx; + byte[] mask = this.updateFlags[flagOffset]; + ChunkRender.renderUnderground(this.mw.blockColours, new RenderChunk(chunk), this.pixels, pixelOffset, this.textureSize, this.py, mask); + } + flagOffset += 1; + } + } + + this.renderToTexture(this.py + 1); + } + + private void clearFlags() + { + for (byte[] chunkFlags : this.updateFlags) + { + Arrays.fill(chunkFlags, ChunkRender.FLAG_UNPROCESSED); + } + } + + private void processBlock(int xi, int y, int zi) + { + int x = (this.updateX << 4) + xi; + int z = (this.updateZ << 4) + zi; + + int xDist = this.px - x; + int zDist = this.pz - z; + + if (((xDist * xDist) + (zDist * zDist)) <= 256) + { + if (this.isChunkInTexture(x >> 4, z >> 4)) + { + int chunkOffset = ((zi >> 4) * 3) + (xi >> 4); + int columnXi = xi & 0xf; + int columnZi = zi & 0xf; + int columnOffset = (columnZi << 4) + columnXi; + byte columnFlag = this.updateFlags[chunkOffset][columnOffset]; + + if (columnFlag == ChunkRender.FLAG_UNPROCESSED) + { + // if column not yet processed + WorldClient world = this.mw.mc.theWorld; + Block block = world.getBlockState(new BlockPos(x, y, z)).getBlock(); + if ((block == null) || !block.isOpaqueCube()) + { + // if block is not opaque + this.updateFlags[chunkOffset][columnOffset] = ChunkRender.FLAG_NON_OPAQUE; + this.processBlock(xi + 1, y, zi); + this.processBlock(xi - 1, y, zi); + this.processBlock(xi, y, zi + 1); + this.processBlock(xi, y, zi - 1); + } + else + { + // block is opaque + this.updateFlags[chunkOffset][columnOffset] = ChunkRender.FLAG_OPAQUE; + } + } + } + } + } + +} diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java index 7f0f7807..f7a47038 100644 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -1,10 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.config.Config; - - -public class FullScreenMapMode extends MapMode { - public FullScreenMapMode() { - super(Config.fullScreenMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; + +public class FullScreenMapMode extends MapMode +{ + public FullScreenMapMode() + { + super(Config.fullScreenMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java index 92470a19..f68fabcb 100644 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -1,10 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.config.Config; - - -public class LargeMapMode extends MapMode { - public LargeMapMode() { - super(Config.largeMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; + +public class LargeMapMode extends MapMode +{ + public LargeMapMode() + { + super(Config.largeMap); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 256e47b5..4c78c657 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -1,233 +1,269 @@ -package mapwriter.map.mapmode; - -import java.awt.Point; - -import mapwriter.config.MapModeConfig; -import mapwriter.map.MapView; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; - -public class MapMode { - private int sw = 320; - private int sh = 240; - private double screenScalingFactor = 1.0; - - // calculated before every frame drawn by updateMapDimensions - public int xTranslation = 0; - public int yTranslation = 0; - public int x = -25; - public int y = -25; - public int w = 50; - public int h = 50; - public int wPixels = 50; - public int hPixels = 50; - - public int marginTop = 10; - public int marginBottom = -1; - public int marginLeft = -1; - public int marginRight = 10; - - public String lastPos = MapModeConfig.miniMapPositionStringArray[0]; - - // config settings - - public int textX = 0; - public int textY = 0; - public int textColour = 0xffffffff; - - public MapModeConfig config; - - public MapMode(MapModeConfig config) { - this.config = config; - updateMargin(); - } - - public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { - if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { - this.sw = sw; - this.sh = sh; - this.screenScalingFactor = scaling; - this.update(); - } - } - - public void setScreenRes() { - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); - } - - public void updateMargin() - { - if (this.lastPos.equals(this.config.Position)) - { - return; - } - - //top right - if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[0])) - { - marginTop = 10; - marginBottom = -1; - marginLeft = -1; - marginRight = 10; - } - //top left - else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[1])) - { - marginTop = 10; - marginBottom = -1; - marginLeft = 10; - marginRight = -1; - } - //botom right - else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[2])) - { - marginTop = -1; - marginBottom = 40; - marginLeft = -1; - marginRight = 10; - } - //botom left - else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[3])) - { - marginTop = -1; - marginBottom = 40; - marginLeft = 10; - marginRight = -1; - } - else if (this.config.Position.equals("FullScreen")) - { - marginTop = 0; - marginBottom = 0; - marginLeft = 0; - marginRight = 0; - } - else if (this.config.Position.equals("Large")) - { - marginTop = 10; - marginBottom = 40; - marginLeft = 40; - marginRight = 40; - } - this.update(); - } - - private void update() { - int size = (this.sh * this.config.heightPercent) / 100; - int x, y; - - // calculate map x position and width - if ((marginLeft >= 0) && (marginRight >= 0)) { - x = marginLeft; - this.w = this.sw - marginLeft - marginRight; - } else if (marginLeft >= 0) { - x = marginLeft; - this.w = size; - } else if (marginRight >= 0) { - x = this.sw - size - marginRight; - this.w = size; - } else { - x = (this.sw - size) / 2; - this.w = size; - } - - // calculate map y position and height - if ((marginTop >= 0) && (marginBottom >= 0)) { - y = marginTop; - this.h = this.sh - marginTop - marginBottom; - } else if (marginTop >= 0) { - y = marginTop; - this.h = size; - } else if (marginBottom >= 0) { - y = this.sh - size - marginBottom; - this.h = size; - } else { - y = (this.sh - size) / 2; - this.h = size; - } - - // make sure width and height are multiples of 2 - this.w &= -2; - this.h &= -2; - - this.xTranslation = x + (this.w >> 1); - this.yTranslation = y + (this.h >> 1); - - if (this.config.circular) { - this.w = this.h; - } - - this.x = -(this.w >> 1); - this.y = -(this.h >> 1); - - this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); - this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); - - // calculate coords display location - this.textX = 0; - this.textY = (this.h >> 1) + 4; - - //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); - //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", - // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); - } - - public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { - double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); - double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); - int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); - int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); - return new Point(bx, bz); - } - - public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { - double xNorm = (bX - mapView.getX()) / mapView.getWidth(); - double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); - return new Point.Double(this.w * xNorm, this.h * zNorm); - } - - public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { - double xRel = (bX - mapView.getX()) / mapView.getWidth(); - double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); - double limit = 0.49; - - if (!this.config.circular) { - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - if (zRel < -limit) { - xRel = -limit * xRel / zRel; - zRel = -limit; - } - if (zRel > limit) { - xRel = limit * xRel / zRel; - zRel = limit; - } - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - } else { - double dSq = (xRel * xRel) + (zRel * zRel); - if (dSq > (limit * limit)) { - double a = Math.atan2(zRel, xRel); - xRel = limit * Math.cos(a); - zRel = limit * Math.sin(a); - } - } - - // multiply by the overlay size and add the overlay position to - // get the position within the overlay in screen coordinates - return new Point.Double(this.w * xRel, this.h * zRel); - } -} +package mapwriter.map.mapmode; + +import java.awt.Point; + +import mapwriter.config.MapModeConfig; +import mapwriter.map.MapView; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; + +public class MapMode +{ + private int sw = 320; + private int sh = 240; + private double screenScalingFactor = 1.0; + + // calculated before every frame drawn by updateMapDimensions + public int xTranslation = 0; + public int yTranslation = 0; + public int x = -25; + public int y = -25; + public int w = 50; + public int h = 50; + public int wPixels = 50; + public int hPixels = 50; + + public int marginTop = 10; + public int marginBottom = -1; + public int marginLeft = -1; + public int marginRight = 10; + + public String lastPos = MapModeConfig.miniMapPositionStringArray[0]; + + // config settings + + public int textX = 0; + public int textY = 0; + public int textColour = 0xffffffff; + + public MapModeConfig config; + + public MapMode(MapModeConfig config) + { + this.config = config; + this.updateMargin(); + } + + public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) + { + if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) + { + this.sw = sw; + this.sh = sh; + this.screenScalingFactor = scaling; + this.update(); + } + } + + public void setScreenRes() + { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); + } + + public void updateMargin() + { + if (this.lastPos.equals(this.config.Position)) + { + return; + } + + // top right + if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[0])) + { + this.marginTop = 10; + this.marginBottom = -1; + this.marginLeft = -1; + this.marginRight = 10; + } + // top left + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[1])) + { + this.marginTop = 10; + this.marginBottom = -1; + this.marginLeft = 10; + this.marginRight = -1; + } + // botom right + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[2])) + { + this.marginTop = -1; + this.marginBottom = 40; + this.marginLeft = -1; + this.marginRight = 10; + } + // botom left + else if (this.config.Position.equals(MapModeConfig.miniMapPositionStringArray[3])) + { + this.marginTop = -1; + this.marginBottom = 40; + this.marginLeft = 10; + this.marginRight = -1; + } + else if (this.config.Position.equals("FullScreen")) + { + this.marginTop = 0; + this.marginBottom = 0; + this.marginLeft = 0; + this.marginRight = 0; + } + else if (this.config.Position.equals("Large")) + { + this.marginTop = 10; + this.marginBottom = 40; + this.marginLeft = 40; + this.marginRight = 40; + } + this.update(); + } + + private void update() + { + int size = (this.sh * this.config.heightPercent) / 100; + int x, y; + + // calculate map x position and width + if ((this.marginLeft >= 0) && (this.marginRight >= 0)) + { + x = this.marginLeft; + this.w = this.sw - this.marginLeft - this.marginRight; + } + else if (this.marginLeft >= 0) + { + x = this.marginLeft; + this.w = size; + } + else if (this.marginRight >= 0) + { + x = this.sw - size - this.marginRight; + this.w = size; + } + else + { + x = (this.sw - size) / 2; + this.w = size; + } + + // calculate map y position and height + if ((this.marginTop >= 0) && (this.marginBottom >= 0)) + { + y = this.marginTop; + this.h = this.sh - this.marginTop - this.marginBottom; + } + else if (this.marginTop >= 0) + { + y = this.marginTop; + this.h = size; + } + else if (this.marginBottom >= 0) + { + y = this.sh - size - this.marginBottom; + this.h = size; + } + else + { + y = (this.sh - size) / 2; + this.h = size; + } + + // make sure width and height are multiples of 2 + this.w &= -2; + this.h &= -2; + + this.xTranslation = x + (this.w >> 1); + this.yTranslation = y + (this.h >> 1); + + if (this.config.circular) + { + this.w = this.h; + } + + this.x = -(this.w >> 1); + this.y = -(this.h >> 1); + + this.wPixels = (int) Math.round((this.w) * this.screenScalingFactor); + this.hPixels = (int) Math.round((this.h) * this.screenScalingFactor); + + // calculate coords display location + this.textX = 0; + this.textY = (this.h >> 1) + 4; + + // MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, + // this.y, this.w, this.h, this.sw, this.sh); + // MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", + // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, + // size); + } + + public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) + { + double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); + double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); + int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); + int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); + return new Point(bx, bz); + } + + public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) + { + double xNorm = (bX - mapView.getX()) / mapView.getWidth(); + double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); + return new Point.Double(this.w * xNorm, this.h * zNorm); + } + + public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) + { + double xRel = (bX - mapView.getX()) / mapView.getWidth(); + double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); + double limit = 0.49; + + if (!this.config.circular) + { + if (xRel < -limit) + { + zRel = (-limit * zRel) / xRel; + xRel = -limit; + } + if (xRel > limit) + { + zRel = (limit * zRel) / xRel; + xRel = limit; + } + if (zRel < -limit) + { + xRel = (-limit * xRel) / zRel; + zRel = -limit; + } + if (zRel > limit) + { + xRel = (limit * xRel) / zRel; + zRel = limit; + } + if (xRel < -limit) + { + zRel = (-limit * zRel) / xRel; + xRel = -limit; + } + if (xRel > limit) + { + zRel = (limit * zRel) / xRel; + xRel = limit; + } + } + else + { + double dSq = (xRel * xRel) + (zRel * zRel); + if (dSq > (limit * limit)) + { + double a = Math.atan2(zRel, xRel); + xRel = limit * Math.cos(a); + zRel = limit * Math.sin(a); + } + } + + // multiply by the overlay size and add the overlay position to + // get the position within the overlay in screen coordinates + return new Point.Double(this.w * xRel, this.h * zRel); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java index d0ef1317..1930cdf3 100644 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -1,10 +1,11 @@ -package mapwriter.map.mapmode; - -import mapwriter.config.Config; - - -public class SmallMapMode extends MapMode { - public SmallMapMode() { - super(Config.smallMap); - } -} +package mapwriter.map.mapmode; + +import mapwriter.config.Config; + +public class SmallMapMode extends MapMode +{ + public SmallMapMode() + { + super(Config.smallMap); + } +} diff --git a/src/main/java/mapwriter/overlay/OverlayChecker.java b/src/main/java/mapwriter/overlay/OverlayChecker.java index 8816a6ee..729026e1 100644 --- a/src/main/java/mapwriter/overlay/OverlayChecker.java +++ b/src/main/java/mapwriter/overlay/OverlayChecker.java @@ -1,110 +1,152 @@ -package mapwriter.overlay; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.util.MathHelper; - -public class OverlayChecker implements IMwDataProvider { - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x90ffffff; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - - // We should pass the center of the map too to reduce the display like in this case - // and the zoom lvl, to provide higher level informations - - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - ArrayList chunks = new ArrayList(); - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++){ - if ((x+z)%2 == 0) - chunks.add(new ChunkOverlay(x, z)); - }; - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - - } - - @Override - public void onOverlayActivated(MapView mapview) { - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - - return false; - } - -} +package mapwriter.overlay; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.util.MathHelper; + +public class OverlayChecker implements IMwDataProvider +{ + + public class ChunkOverlay implements IMwChunkOverlay + { + + Point coord; + + public ChunkOverlay(int x, int z) + { + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() + { + return this.coord; + } + + @Override + public int getColor() + { + return 0x90ffffff; + } + + @Override + public float getFilling() + { + return 1.0f; + } + + @Override + public boolean hasBorder() + { + return true; + } + + @Override + public float getBorderWidth() + { + return 0.5f; + } + + @Override + public int getBorderColor() + { + return 0xff000000; + } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) + { + + // We should pass the center of the map too to reduce the display like + // in this case + // and the zoom lvl, to provide higher level informations + + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + ArrayList chunks = new ArrayList(); + for (int x = limitMinX; x <= limitMaxX; x++) + { + for (int z = limitMinZ; z <= limitMaxZ; z++) + { + if (((x + z) % 2) == 0) + { + chunks.add(new ChunkOverlay(x, z)); + } + } + } + ; + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) + { + return ""; + } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) + { + } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) + { + } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) + { + + } + + @Override + public void onZoomChanged(int level, MapView mapview) + { + + } + + @Override + public void onOverlayActivated(MapView mapview) + { + + } + + @Override + public void onOverlayDeactivated(MapView mapview) + { + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) + { + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) + { + + return false; + } + +} diff --git a/src/main/java/mapwriter/overlay/OverlayGrid.java b/src/main/java/mapwriter/overlay/OverlayGrid.java index f8556349..9c85a11b 100644 --- a/src/main/java/mapwriter/overlay/OverlayGrid.java +++ b/src/main/java/mapwriter/overlay/OverlayGrid.java @@ -1,104 +1,143 @@ -package mapwriter.overlay; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.util.MathHelper; - -public class OverlayGrid implements IMwDataProvider { - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x00ffffff; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - ArrayList chunks = new ArrayList(); - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++) - chunks.add(new ChunkOverlay(x, z)); - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - - } - - @Override - public void onOverlayActivated(MapView mapview) { - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - - return false; - } - -} +package mapwriter.overlay; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.util.MathHelper; + +public class OverlayGrid implements IMwDataProvider +{ + + public class ChunkOverlay implements IMwChunkOverlay + { + + Point coord; + + public ChunkOverlay(int x, int z) + { + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() + { + return this.coord; + } + + @Override + public int getColor() + { + return 0x00ffffff; + } + + @Override + public float getFilling() + { + return 1.0f; + } + + @Override + public boolean hasBorder() + { + return true; + } + + @Override + public float getBorderWidth() + { + return 0.5f; + } + + @Override + public int getBorderColor() + { + return 0xff000000; + } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) + { + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + ArrayList chunks = new ArrayList(); + for (int x = limitMinX; x <= limitMaxX; x++) + { + for (int z = limitMinZ; z <= limitMaxZ; z++) + { + chunks.add(new ChunkOverlay(x, z)); + } + } + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) + { + return ""; + } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) + { + } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) + { + } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) + { + + } + + @Override + public void onZoomChanged(int level, MapView mapview) + { + + } + + @Override + public void onOverlayActivated(MapView mapview) + { + + } + + @Override + public void onOverlayDeactivated(MapView mapview) + { + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) + { + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) + { + + return false; + } + +} diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java index 569a6838..a106aecc 100644 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -1,151 +1,197 @@ -package mapwriter.overlay; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.Random; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.util.MathHelper; - -public class OverlaySlime implements IMwDataProvider { - - public static boolean seedFound = false; - public static boolean seedAsked = false; - private static long seed = -1; - - public static void setSeed(long seed){ - OverlaySlime.seed = seed; - OverlaySlime.seedFound = true; - } - - public static void askSeed(){ - EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; - if(player == null) return; - player.sendChatMessage("/seed"); //Send the /seed command to the server - seedAsked = true; - } - - public static void reset(){ - seedFound = false; - seedAsked = false; - seed = -1; - } - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x5000ff00; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - - // We should pass the center of the map too to reduce the display like in this case - // and the zoom lvl, to provide higher level informations - - if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.getDimensionId() != dim) - return new ArrayList(); - - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - if(!seedFound && !seedAsked){ - //We don't have the seed and we didn't ask for it yet. Let's go! - askSeed(); - } - - ArrayList chunks = new ArrayList(); - if(seedFound){ //If we know the seed, then add the overlay - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++){ - - Random rnd = new Random(seed + - (long) (x * x * 0x4c1906) + - (long) (x * 0x5ac0db) + - (long) (z * z) * 0x4307a7L + - (long) (z * 0x5f24f) ^ 0x3ad8025f); - if (rnd.nextInt(10) == 0){ - chunks.add(new ChunkOverlay(x, z)); - } - } - } - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - - } - - @Override - public void onOverlayActivated(MapView mapview) { - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - return false; - } - -} +package mapwriter.overlay; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.Random; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.util.MathHelper; + +public class OverlaySlime implements IMwDataProvider +{ + + public static boolean seedFound = false; + public static boolean seedAsked = false; + private static long seed = -1; + + public static void setSeed(long seed) + { + OverlaySlime.seed = seed; + OverlaySlime.seedFound = true; + } + + public static void askSeed() + { + EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; + if (player == null) + { + return; + } + player.sendChatMessage("/seed"); // Send the /seed command to the server + seedAsked = true; + } + + public static void reset() + { + seedFound = false; + seedAsked = false; + seed = -1; + } + + public class ChunkOverlay implements IMwChunkOverlay + { + + Point coord; + + public ChunkOverlay(int x, int z) + { + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() + { + return this.coord; + } + + @Override + public int getColor() + { + return 0x5000ff00; + } + + @Override + public float getFilling() + { + return 1.0f; + } + + @Override + public boolean hasBorder() + { + return true; + } + + @Override + public float getBorderWidth() + { + return 0.5f; + } + + @Override + public int getBorderColor() + { + return 0xff000000; + } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) + { + + // We should pass the center of the map too to reduce the display like + // in this case + // and the zoom lvl, to provide higher level informations + + if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.getDimensionId() != dim) + { + return new ArrayList(); + } + + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + if (!seedFound && !seedAsked) + { + // We don't have the seed and we didn't ask for it yet. Let's go! + askSeed(); + } + + ArrayList chunks = new ArrayList(); + if (seedFound) + { // If we know the seed, then add the overlay + for (int x = limitMinX; x <= limitMaxX; x++) + { + for (int z = limitMinZ; z <= limitMaxZ; z++) + { + + Random rnd = new Random((seed + x * x * 0x4c1906 + x * 0x5ac0db + (z * z * 0x4307a7L) + z * 0x5f24f) ^ 0x3ad8025f); + if (rnd.nextInt(10) == 0) + { + chunks.add(new ChunkOverlay(x, z)); + } + } + } + } + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) + { + return ""; + } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) + { + } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) + { + } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) + { + + } + + @Override + public void onZoomChanged(int level, MapView mapview) + { + + } + + @Override + public void onOverlayActivated(MapView mapview) + { + + } + + @Override + public void onOverlayDeactivated(MapView mapview) + { + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) + { + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) + { + return false; + } + +} diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 813842b6..74d2dc8b 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -1,607 +1,696 @@ -package mapwriter.region; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Scanner; - -import mapwriter.util.Logging; -import mapwriter.util.Render; -import net.minecraft.block.Block; - -public class BlockColours { - - public static final int MAX_BLOCKS = 4096; - public static final int MAX_META = 16; - public static final int MAX_BIOMES = 256; - - public static final String biomeSectionString = "[biomes]"; - public static final String blockSectionString = "[blocks]"; - - private int[] waterMultiplierArray = new int[MAX_BIOMES]; - private int[] grassMultiplierArray = new int[MAX_BIOMES]; - private int[] foliageMultiplierArray = new int[MAX_BIOMES]; - private LinkedHashMap bcMap = new LinkedHashMap(); - - public enum BlockType { - NORMAL, GRASS, LEAVES, FOLIAGE, WATER, OPAQUE - } - - public BlockColours() { - Arrays.fill(this.waterMultiplierArray, 0xffffff); - Arrays.fill(this.grassMultiplierArray, 0xffffff); - Arrays.fill(this.foliageMultiplierArray, 0xffffff); - } - - public String CombineBlockMeta(String BlockName, int meta) { - return BlockName + " " + meta; - } - - public String CombineBlockMeta(String BlockName, String meta) { - return BlockName + " " + meta; - } - - public int getColour(String BlockName, int meta) { - String BlockAndMeta = CombineBlockMeta(BlockName, meta); - String BlockAndWildcard = CombineBlockMeta(BlockName, "*"); - - BlockData data = new BlockData(); - - if (this.bcMap.containsKey(BlockAndMeta)) { - data = this.bcMap.get(BlockAndMeta); - } else if (this.bcMap.containsKey(BlockAndWildcard)) { - data = this.bcMap.get(BlockAndWildcard); - } - return data.color; - } - - public int getColour(int BlockAndMeta) { - Block block = Block.getBlockById(BlockAndMeta >> 4); - int meta = BlockAndMeta & 0xf; - return getColour(block.delegate.name(), meta); - } - - public void setColour(String BlockName, String meta, int colour) { - String BlockAndMeta = CombineBlockMeta(BlockName, meta); - - if (meta.equals("*")) { - for (int i = 0; i < 16; i++) { - setColour(BlockName, String.valueOf(i), colour); - } - } - - if (this.bcMap.containsKey(BlockAndMeta)) { - BlockData data = this.bcMap.get(BlockAndMeta); - data.color = colour; - } else { - BlockData data = new BlockData(); - data.color = colour; - this.bcMap.put(BlockAndMeta, data); - } - } - - private int getGrassColourMultiplier(int biome) { - return (this.grassMultiplierArray != null) && (biome >= 0) - && (biome < this.grassMultiplierArray.length) ? this.grassMultiplierArray[biome] - : 0xffffff; - } - - private int getWaterColourMultiplier(int biome) { - return (this.waterMultiplierArray != null) && (biome >= 0) - && (biome < this.waterMultiplierArray.length) ? this.waterMultiplierArray[biome] - : 0xffffff; - } - - private int getFoliageColourMultiplier(int biome) { - return (this.foliageMultiplierArray != null) && (biome >= 0) - && (biome < this.foliageMultiplierArray.length) ? this.foliageMultiplierArray[biome] - : 0xffffff; - } - - public int getBiomeColour(String BlockName, int meta, int biome) { - int colourMultiplier = 0xffffff; - - if (this.bcMap.containsKey(CombineBlockMeta(BlockName, meta))) { - switch (this.bcMap.get(CombineBlockMeta(BlockName, meta)).type) { - case GRASS: - colourMultiplier = getGrassColourMultiplier(biome); - break; - case LEAVES: - case FOLIAGE: - colourMultiplier = getFoliageColourMultiplier(biome); - break; - case WATER: - colourMultiplier = getWaterColourMultiplier(biome); - break; - default: - colourMultiplier = 0xffffff; - break; - } - } - return colourMultiplier; - } - - public int getBiomeColour(int BlockAndMeta, int biome) { - Block block = Block.getBlockById(BlockAndMeta >> 4); - int meta = BlockAndMeta & 0xf; - return getBiomeColour(block.delegate.name(), meta, biome); - } - - public void setBiomeWaterShading(int biomeID, int colour) { - this.waterMultiplierArray[biomeID & 0xff] = colour; - } - - public void setBiomeGrassShading(int biomeID, int colour) { - this.grassMultiplierArray[biomeID & 0xff] = colour; - } - - public void setBiomeFoliageShading(int biomeID, int colour) { - this.foliageMultiplierArray[biomeID & 0xff] = colour; - } - - private static BlockType getBlockTypeFromString(String typeString) { - BlockType blockType = BlockType.NORMAL; - if (typeString.equalsIgnoreCase("normal")) { - blockType = BlockType.NORMAL; - } else if (typeString.equalsIgnoreCase("grass")) { - blockType = BlockType.GRASS; - } else if (typeString.equalsIgnoreCase("leaves")) { - blockType = BlockType.LEAVES; - } else if (typeString.equalsIgnoreCase("foliage")) { - blockType = BlockType.FOLIAGE; - } else if (typeString.equalsIgnoreCase("water")) { - blockType = BlockType.WATER; - } else if (typeString.equalsIgnoreCase("opaque")) { - blockType = BlockType.OPAQUE; - } else { - Logging.logWarning("unknown block type '%s'", typeString); - } - return blockType; - } - - private static String getBlockTypeAsString(BlockType blockType) { - String s = "normal"; - switch (blockType) { - case NORMAL: - s = "normal"; - break; - case GRASS: - s = "grass"; - break; - case LEAVES: - s = "leaves"; - break; - case FOLIAGE: - s = "foliage"; - break; - case WATER: - s = "water"; - break; - case OPAQUE: - s = "opaque"; - break; - } - return s; - } - - public BlockType getBlockType(String BlockName, int meta) { - String BlockAndMeta = CombineBlockMeta(BlockName, meta); - String BlockAndWildcard = CombineBlockMeta(BlockName, "*"); - - BlockData data = new BlockData(); - - if (this.bcMap.containsKey(BlockAndMeta)) { - data = this.bcMap.get(BlockAndMeta); - } else if (this.bcMap.containsKey(BlockAndWildcard)) { - data = this.bcMap.get(BlockAndWildcard); - } - return data.type; - } - - public BlockType getBlockType(int BlockAndMeta) { - Block block = Block.getBlockById(BlockAndMeta >> 4); - int meta = BlockAndMeta & 0xf; - return getBlockType(block.delegate.name(), meta); - } - - public void setBlockType(String BlockName, String meta, BlockType type) { - String BlockAndMeta = CombineBlockMeta(BlockName, meta); - - if (meta.equals("*")) { - for (int i = 0; i < 16; i++) { - setBlockType(BlockName, String.valueOf(i), type); - } - return; - } - - if (this.bcMap.containsKey(BlockAndMeta)) { - BlockData data = this.bcMap.get(BlockAndMeta); - data.type = type; - data.color = adjustBlockColourFromType(BlockName, meta, type, - data.color); - } else { - BlockData data = new BlockData(); - data.type = type; - this.bcMap.put(BlockAndMeta, data); - } - } - - private static int adjustBlockColourFromType(String BlockName, String meta, - BlockType type, int blockColour) { - // for normal blocks multiply the block colour by the render colour. - // for other blocks the block colour will be multiplied by the biome - // colour. - Block block = Block.getBlockFromName(BlockName); - - switch (type) { - - case OPAQUE: - blockColour |= 0xff000000; - case NORMAL: - // fix crash when mods don't implement getRenderColor for all - // block meta values. - try { - int renderColour = block.getRenderColor(block - .getStateFromMeta(Integer.parseInt(meta) & 0xf)); - if (renderColour != 0xffffff) { - blockColour = Render.multiplyColours(blockColour, - 0xff000000 | renderColour); - } - } catch (RuntimeException e) { - // do nothing - } - break; - case LEAVES: - // leaves look weird on the map if they are not opaque. - // they also look too dark if the render colour is applied. - blockColour |= 0xff000000; - break; - case GRASS: - //the icon returns the dirt texture so hardcode it to the grey undertexture. - blockColour = 0xff9b9b9b; - default: - break; - } - return blockColour; - } - - public static int getColourFromString(String s) { - return (int) (Long.parseLong(s, 16) & 0xffffffffL); - } - - // - // Methods for loading block colours from file: - // - - // read biome colour multiplier values. - // line format is: - // biome - // accepts "*" wildcard for biome id (meaning for all biomes). - private void loadBiomeLine(String[] split) { - try { - int startBiomeId = 0; - int endBiomeId = MAX_BIOMES; - if (!split[1].equals("*")) { - startBiomeId = Integer.parseInt(split[1]); - endBiomeId = startBiomeId + 1; - } - - if ((startBiomeId >= 0) && (startBiomeId < MAX_BIOMES)) { - int waterMultiplier = getColourFromString(split[2]) & 0xffffff; - int grassMultiplier = getColourFromString(split[3]) & 0xffffff; - int foliageMultiplier = getColourFromString(split[4]) & 0xffffff; - - for (int biomeId = startBiomeId; biomeId < endBiomeId; biomeId++) { - this.setBiomeWaterShading(biomeId, waterMultiplier); - this.setBiomeGrassShading(biomeId, grassMultiplier); - this.setBiomeFoliageShading(biomeId, foliageMultiplier); - } - } else { - Logging.logWarning("biome ID '%d' out of range", - startBiomeId); - } - - } catch (NumberFormatException e) { - Logging.logWarning( - "invalid biome colour line '%s %s %s %s %s'", split[0], - split[1], split[2], split[3], split[4]); - } - } - - // read block colour values. - // line format is: - // block - // the biome id, meta value, and colour code are in hex. - // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or - // meta values). - private void loadBlockLine(String[] split) { - try { - // block colour line - int colour = getColourFromString(split[3]); - this.setColour(split[1], split[2], colour); - - } catch (NumberFormatException e) { - Logging.logWarning("invalid block colour line '%s %s %s %s'", - split[0], split[1], split[2], split[3]); - } - } - - private void loadBlockTypeLine(String[] split) { - try { - // block type line - BlockType type = getBlockTypeFromString(split[3]); - this.setBlockType(split[1], split[2], type); - } catch (NumberFormatException e) { - Logging.logWarning("invalid block colour line '%s %s %s %s'", - split[0], split[1], split[2], split[3]); - } - } - - public void loadFromFile(File f) { - Scanner fin = null; - try { - fin = new Scanner(new FileReader(f)); - - while (fin.hasNextLine()) { - // get next line and remove comments (part of line after #) - String line = fin.nextLine().split("#")[0].trim(); - if (line.length() > 0) { - String[] lineSplit = line.split(" "); - if (lineSplit[0].equals("biome") && (lineSplit.length == 5)) { - this.loadBiomeLine(lineSplit); - } else if (lineSplit[0].equals("block") - && (lineSplit.length == 4)) { - this.loadBlockLine(lineSplit); - } else if (lineSplit[0].equals("blocktype") - && (lineSplit.length == 4)) { - this.loadBlockTypeLine(lineSplit); - } else { - Logging.logWarning( - "invalid map colour line '%s'", line); - } - } - } - } catch (IOException e) { - Logging.logError("loading block colours: no such file '%s'", - f); - - } finally { - if (fin != null) { - fin.close(); - } - } - } - - // - // Methods for saving block colours to file. - // - - // save biome colour multipliers to a file. - public void saveBiomes(Writer fout) throws IOException { - fout.write("biome * ffffff ffffff ffffff\n"); - - for (int biomeId = 0; biomeId < MAX_BIOMES; biomeId++) { - int waterMultiplier = this.getWaterColourMultiplier(biomeId) & 0xffffff; - int grassMultiplier = this.getGrassColourMultiplier(biomeId) & 0xffffff; - int foliageMultiplier = this.getFoliageColourMultiplier(biomeId) & 0xffffff; - - // don't add lines that are covered by the default. - if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) - || (foliageMultiplier != 0xffffff)) { - fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, - waterMultiplier, grassMultiplier, foliageMultiplier)); - } - } - } - - private static String getMostOccurringKey(Map map, - String defaultItem) { - // find the most commonly occurring key in a hash map. - // only return a key if there is more than 1. - int maxCount = 1; - String mostOccurringKey = defaultItem; - for (Entry entry : map.entrySet()) { - String key = entry.getKey(); - int count = entry.getValue(); - - if (count > maxCount) { - maxCount = count; - mostOccurringKey = key; - } - } - - return mostOccurringKey; - } - - // to use the least number of lines possible find the most commonly - // occurring - // item for the different meta values of a block. - // an 'item' is either a block colour or a block type. - // the most commonly occurring item is then used as the wildcard entry for - // the block, and all non matching items added afterwards. - private static void writeMinimalBlockLines(Writer fout, String lineStart, - List items, String defaultItem) throws IOException { - - Map frequencyMap = new HashMap(); - - // first count the number of occurrences of each item. - for (String item : items) { - int count = 0; - if (frequencyMap.containsKey(item)) { - count = frequencyMap.get(item); - } - frequencyMap.put(item, count + 1); - } - - // then find the most commonly occurring item. - String mostOccurringItem = getMostOccurringKey(frequencyMap, - defaultItem); - - // only add a wildcard line if it actually saves lines. - if (!mostOccurringItem.equals(defaultItem)) { - fout.write(String.format("%s * %s\n", lineStart, mostOccurringItem)); - } - - // add lines for items that don't match the wildcard line. - - int meta = 0; - for (String s : items) { - if (!s.equals(mostOccurringItem) && !s.equals(defaultItem)) { - fout.write(String.format("%s %d %s\n", lineStart, meta, s)); - } - meta++; - } - } - - public void saveBlocks(Writer fout) throws IOException { - fout.write("block * * 00000000\n"); - - String LastBlock = ""; - List colours = new ArrayList(); - - for (Map.Entry entry : bcMap.entrySet()) { - String[] BlockAndMeta = entry.getKey().split(" "); - String block = BlockAndMeta[0]; - - String color = String.format("%08x", entry.getValue().color); - - if (!LastBlock.equals(block) && !LastBlock.isEmpty()) { - String lineStart = String.format("block %s", LastBlock); - writeMinimalBlockLines(fout, lineStart, colours, "00000000"); - - colours.clear(); - } - - colours.add(color); - LastBlock = block; - } - } - - public void saveBlockTypes(Writer fout) throws IOException { - fout.write("blocktype * * normal\n"); - - String LastBlock = ""; - List blockTypes = new ArrayList(); - - for (Map.Entry entry : bcMap.entrySet()) { - String[] BlockAndMeta = entry.getKey().split(" "); - String block = BlockAndMeta[0]; - - String Type = getBlockTypeAsString(entry.getValue().type); - - if (!LastBlock.equals(block) && !LastBlock.isEmpty()) { - String lineStart = String.format("blocktype %s", LastBlock); - writeMinimalBlockLines(fout, lineStart, blockTypes, - getBlockTypeAsString(BlockType.NORMAL)); - - blockTypes.clear(); - } - - blockTypes.add(Type); - LastBlock = block; - } - } - - // save block colours and biome colour multipliers to a file. - public void saveToFile(File f) { - Writer fout = null; - try { - fout = new OutputStreamWriter(new FileOutputStream(f)); - this.saveBiomes(fout); - this.saveBlockTypes(fout); - this.saveBlocks(fout); - - } catch (IOException e) { - Logging.logError( - "saving block colours: could not write to '%s'", f); - - } finally { - if (fout != null) { - try { - fout.close(); - } catch (IOException e) { - } - } - } - } - - public static void writeOverridesFile(File f) { - Writer fout = null; - try { - fout = new OutputStreamWriter(new FileOutputStream(f)); - - fout.write("block minecraft:yellow_flower * 60ffff00 # make dandelions more yellow\n" - + "block minecraft:red_flower 0 60ff0000 # make poppy more red\n" - + "block minecraft:red_flower 1 601c92d6 # make Blue Orchid more red\n" - + "block minecraft:red_flower 2 60b865fb # make Allium more red\n" - + "block minecraft:red_flower 3 60e4eaf2 # make Azure Bluet more red\n" - + "block minecraft:red_flower 4 60d33a17 # make Red Tulip more red\n" - + "block minecraft:red_flower 5 60e17124 # make Orange Tulip more red\n" - + "block minecraft:red_flower 6 60ffffff # make White Tulip more red\n" - + "block minecraft:red_flower 7 60eabeea # make Pink Tulip more red\n" - + "block minecraft:red_flower 8 60eae6ad # make Oxeye Daisy more red\n" - + "block minecraft:double_plant 0 60ffff00 # make Sunflower more Yellow-orrange\n" - + "block minecraft:double_plant 1 d09f78a4 # make Lilac more pink\n" - + "block minecraft:double_plant 4 60ff0000 # make Rose Bush more red\n" - + "block minecraft:double_plant 5 d0e3b8f7 # make Peony more red\n" - + "blocktype minecraft:grass * grass # grass block\n" - + "blocktype minecraft:flowing_water * water # flowing water block\n" - + "blocktype minecraft:water * water # still water block\n" - + "blocktype minecraft:leaves * leaves # leaves block\n" - + "blocktype minecraft:leaves2 * leaves # leaves block\n" - + "blocktype minecraft:leaves 1 opaque # pine leaves (not biome colorized)\n" - + "blocktype minecraft:leaves 2 opaque # birch leaves (not biome colorized)\n" - + "blocktype minecraft:tallgrass * grass # tall grass block\n" - + "blocktype minecraft:vine * foliage # vines block\n" - + "blocktype BiomesOPlenty:grass * grass # BOP grass block\n" - + "blocktype BiomesOPlenty:plant_0 * grass # BOP plant block\n" - + "blocktype BiomesOPlenty:plant_1 * grass # BOP plant block\n" - + "blocktype BiomesOPlenty:leaves_0 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:leaves_1 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:leaves_2 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:leaves_3 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:leaves_4 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:leaves_5 * leaves # BOP Leave block\n" - + "blocktype BiomesOPlenty:tree_moss * foliage # biomes o plenty tree moss\n" - ); - //TODO: Find out the names and readd these overwrites - // + "blocktype 2164 * leaves # twilight forest leaves\n" - // + "blocktype 2177 * leaves # twilight forest magic leaves\n" - - // + "blocktype 2204 * leaves # extrabiomesXL green leaves\n" - // + "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" - - // + "blocktype 3257 * opaque # natura berry bush\n" - // + "blocktype 3272 * opaque # natura darkwood leaves\n" - // + "blocktype 3259 * leaves # natura flora leaves\n" - // + "blocktype 3278 * opaque # natura rare leaves\n" - // + "blocktype 3258 * opaque # natura sakura leaves\n" - } catch (IOException e) { - Logging.logError( - "saving block overrides: could not write to '%s'", f); - - } finally { - if (fout != null) { - try { - fout.close(); - } catch (IOException e) { - } - } - } - } - - public class BlockData { - public int color = 0; - public BlockType type = BlockType.NORMAL; - } -} +package mapwriter.region; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; + +import mapwriter.util.Logging; +import mapwriter.util.Render; +import net.minecraft.block.Block; + +public class BlockColours +{ + + public static final int MAX_BLOCKS = 4096; + public static final int MAX_META = 16; + public static final int MAX_BIOMES = 256; + + public static final String biomeSectionString = "[biomes]"; + public static final String blockSectionString = "[blocks]"; + + private int[] waterMultiplierArray = new int[MAX_BIOMES]; + private int[] grassMultiplierArray = new int[MAX_BIOMES]; + private int[] foliageMultiplierArray = new int[MAX_BIOMES]; + private LinkedHashMap bcMap = new LinkedHashMap(); + + public enum BlockType + { + NORMAL, + GRASS, + LEAVES, + FOLIAGE, + WATER, + OPAQUE + } + + public BlockColours() + { + Arrays.fill(this.waterMultiplierArray, 0xffffff); + Arrays.fill(this.grassMultiplierArray, 0xffffff); + Arrays.fill(this.foliageMultiplierArray, 0xffffff); + } + + public String CombineBlockMeta(String BlockName, int meta) + { + return BlockName + " " + meta; + } + + public String CombineBlockMeta(String BlockName, String meta) + { + return BlockName + " " + meta; + } + + public int getColour(String BlockName, int meta) + { + String BlockAndMeta = this.CombineBlockMeta(BlockName, meta); + String BlockAndWildcard = this.CombineBlockMeta(BlockName, "*"); + + BlockData data = new BlockData(); + + if (this.bcMap.containsKey(BlockAndMeta)) + { + data = this.bcMap.get(BlockAndMeta); + } + else if (this.bcMap.containsKey(BlockAndWildcard)) + { + data = this.bcMap.get(BlockAndWildcard); + } + return data.color; + } + + public int getColour(int BlockAndMeta) + { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return this.getColour(block.delegate.name(), meta); + } + + public void setColour(String BlockName, String meta, int colour) + { + String BlockAndMeta = this.CombineBlockMeta(BlockName, meta); + + if (meta.equals("*")) + { + for (int i = 0; i < 16; i++) + { + this.setColour(BlockName, String.valueOf(i), colour); + } + } + + if (this.bcMap.containsKey(BlockAndMeta)) + { + BlockData data = this.bcMap.get(BlockAndMeta); + data.color = colour; + } + else + { + BlockData data = new BlockData(); + data.color = colour; + this.bcMap.put(BlockAndMeta, data); + } + } + + private int getGrassColourMultiplier(int biome) + { + return (this.grassMultiplierArray != null) && (biome >= 0) && (biome < this.grassMultiplierArray.length) ? this.grassMultiplierArray[biome] : 0xffffff; + } + + private int getWaterColourMultiplier(int biome) + { + return (this.waterMultiplierArray != null) && (biome >= 0) && (biome < this.waterMultiplierArray.length) ? this.waterMultiplierArray[biome] : 0xffffff; + } + + private int getFoliageColourMultiplier(int biome) + { + return (this.foliageMultiplierArray != null) && (biome >= 0) && (biome < this.foliageMultiplierArray.length) ? this.foliageMultiplierArray[biome] : 0xffffff; + } + + public int getBiomeColour(String BlockName, int meta, int biome) + { + int colourMultiplier = 0xffffff; + + if (this.bcMap.containsKey(this.CombineBlockMeta(BlockName, meta))) + { + switch (this.bcMap.get(this.CombineBlockMeta(BlockName, meta)).type) + { + case GRASS: + colourMultiplier = this.getGrassColourMultiplier(biome); + break; + case LEAVES: + case FOLIAGE: + colourMultiplier = this.getFoliageColourMultiplier(biome); + break; + case WATER: + colourMultiplier = this.getWaterColourMultiplier(biome); + break; + default: + colourMultiplier = 0xffffff; + break; + } + } + return colourMultiplier; + } + + public int getBiomeColour(int BlockAndMeta, int biome) + { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return this.getBiomeColour(block.delegate.name(), meta, biome); + } + + public void setBiomeWaterShading(int biomeID, int colour) + { + this.waterMultiplierArray[biomeID & 0xff] = colour; + } + + public void setBiomeGrassShading(int biomeID, int colour) + { + this.grassMultiplierArray[biomeID & 0xff] = colour; + } + + public void setBiomeFoliageShading(int biomeID, int colour) + { + this.foliageMultiplierArray[biomeID & 0xff] = colour; + } + + private static BlockType getBlockTypeFromString(String typeString) + { + BlockType blockType = BlockType.NORMAL; + if (typeString.equalsIgnoreCase("normal")) + { + blockType = BlockType.NORMAL; + } + else if (typeString.equalsIgnoreCase("grass")) + { + blockType = BlockType.GRASS; + } + else if (typeString.equalsIgnoreCase("leaves")) + { + blockType = BlockType.LEAVES; + } + else if (typeString.equalsIgnoreCase("foliage")) + { + blockType = BlockType.FOLIAGE; + } + else if (typeString.equalsIgnoreCase("water")) + { + blockType = BlockType.WATER; + } + else if (typeString.equalsIgnoreCase("opaque")) + { + blockType = BlockType.OPAQUE; + } + else + { + Logging.logWarning("unknown block type '%s'", typeString); + } + return blockType; + } + + private static String getBlockTypeAsString(BlockType blockType) + { + String s = "normal"; + switch (blockType) + { + case NORMAL: + s = "normal"; + break; + case GRASS: + s = "grass"; + break; + case LEAVES: + s = "leaves"; + break; + case FOLIAGE: + s = "foliage"; + break; + case WATER: + s = "water"; + break; + case OPAQUE: + s = "opaque"; + break; + } + return s; + } + + public BlockType getBlockType(String BlockName, int meta) + { + String BlockAndMeta = this.CombineBlockMeta(BlockName, meta); + String BlockAndWildcard = this.CombineBlockMeta(BlockName, "*"); + + BlockData data = new BlockData(); + + if (this.bcMap.containsKey(BlockAndMeta)) + { + data = this.bcMap.get(BlockAndMeta); + } + else if (this.bcMap.containsKey(BlockAndWildcard)) + { + data = this.bcMap.get(BlockAndWildcard); + } + return data.type; + } + + public BlockType getBlockType(int BlockAndMeta) + { + Block block = Block.getBlockById(BlockAndMeta >> 4); + int meta = BlockAndMeta & 0xf; + return this.getBlockType(block.delegate.name(), meta); + } + + public void setBlockType(String BlockName, String meta, BlockType type) + { + String BlockAndMeta = this.CombineBlockMeta(BlockName, meta); + + if (meta.equals("*")) + { + for (int i = 0; i < 16; i++) + { + this.setBlockType(BlockName, String.valueOf(i), type); + } + return; + } + + if (this.bcMap.containsKey(BlockAndMeta)) + { + BlockData data = this.bcMap.get(BlockAndMeta); + data.type = type; + data.color = adjustBlockColourFromType(BlockName, meta, type, data.color); + } + else + { + BlockData data = new BlockData(); + data.type = type; + this.bcMap.put(BlockAndMeta, data); + } + } + + private static int adjustBlockColourFromType(String BlockName, String meta, BlockType type, int blockColour) + { + // for normal blocks multiply the block colour by the render colour. + // for other blocks the block colour will be multiplied by the biome + // colour. + Block block = Block.getBlockFromName(BlockName); + + switch (type) + { + + case OPAQUE: + blockColour |= 0xff000000; + case NORMAL: + // fix crash when mods don't implement getRenderColor for all + // block meta values. + try + { + int renderColour = block.getRenderColor(block.getStateFromMeta(Integer.parseInt(meta) & 0xf)); + if (renderColour != 0xffffff) + { + blockColour = Render.multiplyColours(blockColour, 0xff000000 | renderColour); + } + } + catch (RuntimeException e) + { + // do nothing + } + break; + case LEAVES: + // leaves look weird on the map if they are not opaque. + // they also look too dark if the render colour is applied. + blockColour |= 0xff000000; + break; + case GRASS: + // the icon returns the dirt texture so hardcode it to the grey + // undertexture. + blockColour = 0xff9b9b9b; + default: + break; + } + return blockColour; + } + + public static int getColourFromString(String s) + { + return (int) (Long.parseLong(s, 16) & 0xffffffffL); + } + + // + // Methods for loading block colours from file: + // + + // read biome colour multiplier values. + // line format is: + // biome + // accepts "*" wildcard for biome id (meaning for all biomes). + private void loadBiomeLine(String[] split) + { + try + { + int startBiomeId = 0; + int endBiomeId = MAX_BIOMES; + if (!split[1].equals("*")) + { + startBiomeId = Integer.parseInt(split[1]); + endBiomeId = startBiomeId + 1; + } + + if ((startBiomeId >= 0) && (startBiomeId < MAX_BIOMES)) + { + int waterMultiplier = getColourFromString(split[2]) & 0xffffff; + int grassMultiplier = getColourFromString(split[3]) & 0xffffff; + int foliageMultiplier = getColourFromString(split[4]) & 0xffffff; + + for (int biomeId = startBiomeId; biomeId < endBiomeId; biomeId++) + { + this.setBiomeWaterShading(biomeId, waterMultiplier); + this.setBiomeGrassShading(biomeId, grassMultiplier); + this.setBiomeFoliageShading(biomeId, foliageMultiplier); + } + } + else + { + Logging.logWarning("biome ID '%d' out of range", startBiomeId); + } + + } + catch (NumberFormatException e) + { + Logging.logWarning("invalid biome colour line '%s %s %s %s %s'", split[0], split[1], split[2], split[3], split[4]); + } + } + + // read block colour values. + // line format is: + // block + // the biome id, meta value, and colour code are in hex. + // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or + // meta values). + private void loadBlockLine(String[] split) + { + try + { + // block colour line + int colour = getColourFromString(split[3]); + this.setColour(split[1], split[2], colour); + + } + catch (NumberFormatException e) + { + Logging.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); + } + } + + private void loadBlockTypeLine(String[] split) + { + try + { + // block type line + BlockType type = getBlockTypeFromString(split[3]); + this.setBlockType(split[1], split[2], type); + } + catch (NumberFormatException e) + { + Logging.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); + } + } + + public void loadFromFile(File f) + { + Scanner fin = null; + try + { + fin = new Scanner(new FileReader(f)); + + while (fin.hasNextLine()) + { + // get next line and remove comments (part of line after #) + String line = fin.nextLine().split("#")[0].trim(); + if (line.length() > 0) + { + String[] lineSplit = line.split(" "); + if (lineSplit[0].equals("biome") && (lineSplit.length == 5)) + { + this.loadBiomeLine(lineSplit); + } + else if (lineSplit[0].equals("block") && (lineSplit.length == 4)) + { + this.loadBlockLine(lineSplit); + } + else if (lineSplit[0].equals("blocktype") && (lineSplit.length == 4)) + { + this.loadBlockTypeLine(lineSplit); + } + else + { + Logging.logWarning("invalid map colour line '%s'", line); + } + } + } + } + catch (IOException e) + { + Logging.logError("loading block colours: no such file '%s'", f); + + } + finally + { + if (fin != null) + { + fin.close(); + } + } + } + + // + // Methods for saving block colours to file. + // + + // save biome colour multipliers to a file. + public void saveBiomes(Writer fout) throws IOException + { + fout.write("biome * ffffff ffffff ffffff\n"); + + for (int biomeId = 0; biomeId < MAX_BIOMES; biomeId++) + { + int waterMultiplier = this.getWaterColourMultiplier(biomeId) & 0xffffff; + int grassMultiplier = this.getGrassColourMultiplier(biomeId) & 0xffffff; + int foliageMultiplier = this.getFoliageColourMultiplier(biomeId) & 0xffffff; + + // don't add lines that are covered by the default. + if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) || (foliageMultiplier != 0xffffff)) + { + fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, waterMultiplier, grassMultiplier, foliageMultiplier)); + } + } + } + + private static String getMostOccurringKey(Map map, String defaultItem) + { + // find the most commonly occurring key in a hash map. + // only return a key if there is more than 1. + int maxCount = 1; + String mostOccurringKey = defaultItem; + for (Entry entry : map.entrySet()) + { + String key = entry.getKey(); + int count = entry.getValue(); + + if (count > maxCount) + { + maxCount = count; + mostOccurringKey = key; + } + } + + return mostOccurringKey; + } + + // to use the least number of lines possible find the most commonly + // occurring + // item for the different meta values of a block. + // an 'item' is either a block colour or a block type. + // the most commonly occurring item is then used as the wildcard entry for + // the block, and all non matching items added afterwards. + private static void writeMinimalBlockLines(Writer fout, String lineStart, List items, String defaultItem) throws IOException + { + + Map frequencyMap = new HashMap(); + + // first count the number of occurrences of each item. + for (String item : items) + { + int count = 0; + if (frequencyMap.containsKey(item)) + { + count = frequencyMap.get(item); + } + frequencyMap.put(item, count + 1); + } + + // then find the most commonly occurring item. + String mostOccurringItem = getMostOccurringKey(frequencyMap, defaultItem); + + // only add a wildcard line if it actually saves lines. + if (!mostOccurringItem.equals(defaultItem)) + { + fout.write(String.format("%s * %s\n", lineStart, mostOccurringItem)); + } + + // add lines for items that don't match the wildcard line. + + int meta = 0; + for (String s : items) + { + if (!s.equals(mostOccurringItem) && !s.equals(defaultItem)) + { + fout.write(String.format("%s %d %s\n", lineStart, meta, s)); + } + meta++; + } + } + + public void saveBlocks(Writer fout) throws IOException + { + fout.write("block * * 00000000\n"); + + String LastBlock = ""; + List colours = new ArrayList(); + + for (Map.Entry entry : this.bcMap.entrySet()) + { + String[] BlockAndMeta = entry.getKey().split(" "); + String block = BlockAndMeta[0]; + + String color = String.format("%08x", entry.getValue().color); + + if (!LastBlock.equals(block) && !LastBlock.isEmpty()) + { + String lineStart = String.format("block %s", LastBlock); + writeMinimalBlockLines(fout, lineStart, colours, "00000000"); + + colours.clear(); + } + + colours.add(color); + LastBlock = block; + } + } + + public void saveBlockTypes(Writer fout) throws IOException + { + fout.write("blocktype * * normal\n"); + + String LastBlock = ""; + List blockTypes = new ArrayList(); + + for (Map.Entry entry : this.bcMap.entrySet()) + { + String[] BlockAndMeta = entry.getKey().split(" "); + String block = BlockAndMeta[0]; + + String Type = getBlockTypeAsString(entry.getValue().type); + + if (!LastBlock.equals(block) && !LastBlock.isEmpty()) + { + String lineStart = String.format("blocktype %s", LastBlock); + writeMinimalBlockLines(fout, lineStart, blockTypes, getBlockTypeAsString(BlockType.NORMAL)); + + blockTypes.clear(); + } + + blockTypes.add(Type); + LastBlock = block; + } + } + + // save block colours and biome colour multipliers to a file. + public void saveToFile(File f) + { + Writer fout = null; + try + { + fout = new OutputStreamWriter(new FileOutputStream(f)); + this.saveBiomes(fout); + this.saveBlockTypes(fout); + this.saveBlocks(fout); + + } + catch (IOException e) + { + Logging.logError("saving block colours: could not write to '%s'", f); + + } + finally + { + if (fout != null) + { + try + { + fout.close(); + } + catch (IOException e) + { + } + } + } + } + + public static void writeOverridesFile(File f) + { + Writer fout = null; + try + { + fout = new OutputStreamWriter(new FileOutputStream(f)); + + fout.write("block minecraft:yellow_flower * 60ffff00 # make dandelions more yellow\n" + "block minecraft:red_flower 0 60ff0000 # make poppy more red\n" + "block minecraft:red_flower 1 601c92d6 # make Blue Orchid more red\n" + + "block minecraft:red_flower 2 60b865fb # make Allium more red\n" + "block minecraft:red_flower 3 60e4eaf2 # make Azure Bluet more red\n" + "block minecraft:red_flower 4 60d33a17 # make Red Tulip more red\n" + + "block minecraft:red_flower 5 60e17124 # make Orange Tulip more red\n" + "block minecraft:red_flower 6 60ffffff # make White Tulip more red\n" + "block minecraft:red_flower 7 60eabeea # make Pink Tulip more red\n" + + "block minecraft:red_flower 8 60eae6ad # make Oxeye Daisy more red\n" + "block minecraft:double_plant 0 60ffff00 # make Sunflower more Yellow-orrange\n" + "block minecraft:double_plant 1 d09f78a4 # make Lilac more pink\n" + + "block minecraft:double_plant 4 60ff0000 # make Rose Bush more red\n" + "block minecraft:double_plant 5 d0e3b8f7 # make Peony more red\n" + "blocktype minecraft:grass * grass # grass block\n" + "blocktype minecraft:flowing_water * water # flowing water block\n" + + "blocktype minecraft:water * water # still water block\n" + "blocktype minecraft:leaves * leaves # leaves block\n" + "blocktype minecraft:leaves2 * leaves # leaves block\n" + "blocktype minecraft:leaves 1 opaque # pine leaves (not biome colorized)\n" + + "blocktype minecraft:leaves 2 opaque # birch leaves (not biome colorized)\n" + "blocktype minecraft:tallgrass * grass # tall grass block\n" + "blocktype minecraft:vine * foliage # vines block\n" + "blocktype BiomesOPlenty:grass * grass # BOP grass block\n" + + "blocktype BiomesOPlenty:plant_0 * grass # BOP plant block\n" + "blocktype BiomesOPlenty:plant_1 * grass # BOP plant block\n" + "blocktype BiomesOPlenty:leaves_0 * leaves # BOP Leave block\n" + "blocktype BiomesOPlenty:leaves_1 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:leaves_2 * leaves # BOP Leave block\n" + "blocktype BiomesOPlenty:leaves_3 * leaves # BOP Leave block\n" + "blocktype BiomesOPlenty:leaves_4 * leaves # BOP Leave block\n" + "blocktype BiomesOPlenty:leaves_5 * leaves # BOP Leave block\n" + + "blocktype BiomesOPlenty:tree_moss * foliage # biomes o plenty tree moss\n"); + // TODO: Find out the names and readd these overwrites + // + "blocktype 2164 * leaves # twilight forest leaves\n" + // + + // "blocktype 2177 * leaves # twilight forest magic leaves\n" + + // + "blocktype 2204 * leaves # extrabiomesXL green leaves\n" + // + + // "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + + // + "blocktype 3257 * opaque # natura berry bush\n" + // + "blocktype 3272 * opaque # natura darkwood leaves\n" + // + "blocktype 3259 * leaves # natura flora leaves\n" + // + "blocktype 3278 * opaque # natura rare leaves\n" + // + "blocktype 3258 * opaque # natura sakura leaves\n" + } + catch (IOException e) + { + Logging.logError("saving block overrides: could not write to '%s'", f); + + } + finally + { + if (fout != null) + { + try + { + fout.close(); + } + catch (IOException e) + { + } + } + } + } + + public class BlockData + { + public int color = 0; + public BlockType type = BlockType.NORMAL; + } +} diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java index 546ba2b2..cd5e86e5 100644 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -1,238 +1,252 @@ -package mapwriter.region; - -import mapwriter.config.Config; - -public class ChunkRender { - - public static final byte FLAG_UNPROCESSED = 0; - public static final byte FLAG_NON_OPAQUE = 1; - public static final byte FLAG_OPAQUE = 2; - - // values that change how height shading algorithm works - public static final double brightenExponent = 0.35; - public static final double darkenExponent = 0.35; - public static final double brightenAmplitude = 0.7; - public static final double darkenAmplitude = 1.4; - - // get the height shading of a pixel. - // requires the pixel to the west and the pixel to the north to have their - // heights stored in the alpha channel to work. - // the "height" of a pixel is the y value of the first opaque block in - // the block column that created the pixel. - // height values of 0 and 255 are ignored as these are used as the clear - // values for pixels. - public static double getHeightShading(int height, int heightW, int heightN) { - int samples = 0; - int heightDiff = 0; - - if ((heightW > 0) && (heightW < 255)) { - heightDiff += height - heightW; - samples++; - } - - if ((heightN > 0) && (heightN < 255)) { - heightDiff += height - heightN; - samples++; - } - - double heightDiffFactor = 0.0; - if (samples > 0) { - heightDiffFactor = (double) heightDiff / ((double) samples); - } - - // emphasize small differences in height, but as the difference in - // height increases, - // don't increase so much - if (Config.moreRealisticMap) { - return Math.atan(heightDiffFactor) * 0.3; - } - - return (heightDiffFactor >= 0.0) ? Math.pow(heightDiffFactor - * (1 / 255.0), brightenExponent) - * brightenAmplitude : -Math.pow( - -(heightDiffFactor * (1 / 255.0)), darkenExponent) - * darkenAmplitude; - } - - // calculate the colour of a pixel by alpha blending the colour of each - // block - // in a column until an opaque block is reached. - // y is topmost block height to start rendering at. - // for maps without a ceiling y is simply the height of the highest block in - // that chunk. - // for maps with a ceiling y is the height of the first non opaque block - // starting from - // the ceiling. - // - // for every block in the column starting from the highest: - // - get the block colour - // - get the biome shading - // - extract colour components as doubles in the range [0.0, 1.0] - // - the shaded block colour is simply the block colour multiplied - // by the biome shading for each component - // - this shaded block colour is alpha blended with the running - // colour for this column - // - // so the final map colour is an alpha blended stack of all the - // individual shaded block colours in the sequence [yStart .. yEnd] - // - // note that the "front to back" alpha blending algorithm is used - // rather than the more common "back to front". - // - public static int getColumnColour(BlockColours bc, IChunk chunk, int x, - int y, int z, int heightW, int heightN) { - double a = 1.0; - double r = 0.0; - double g = 0.0; - double b = 0.0; - for (; y > 0; y--) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int c1 = bc.getColour(blockAndMeta); - int alpha = (c1 >> 24) & 0xff; - - // this is the color that gets returned for air, so set aplha to 0 - // so the game continues to the next block in the colum - if (c1 == -8650628) { - alpha = 0; - } - - // no need to process block if it is transparent - if (alpha > 0) { - int biome = chunk.getBiome(x, z); - int c2 = bc.getBiomeColour(blockAndMeta, biome); - - // extract colour components as normalized doubles - double c1A = (double) (alpha) / 255.0; - double c1R = (double) ((c1 >> 16) & 0xff) / 255.0; - double c1G = (double) ((c1 >> 8) & 0xff) / 255.0; - double c1B = (double) ((c1 >> 0) & 0xff) / 255.0; - - // c2A is implicitly 1.0 (opaque) - double c2R = (double) ((c2 >> 16) & 0xff) / 255.0; - double c2G = (double) ((c2 >> 8) & 0xff) / 255.0; - double c2B = (double) ((c2 >> 0) & 0xff) / 255.0; - - // alpha blend and multiply - r = r + (a * c1A * c1R * c2R); - g = g + (a * c1A * c1G * c2G); - b = b + (a * c1A * c1B * c2B); - a = a * (1.0 - c1A); - } - // break when an opaque block is encountered - if (alpha == 255) { - break; - } - } - - /* - * // darken blocks depending on how far away they are from this depth - * slice if (depth != 0) { int bottomOfSlice = maxHeight - ((depth + 1) - * * maxHeight / Mw.HEIGHT_LEVELS) - 1; if (yRange[0] < bottomOfSlice) { - * shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / - * (double) maxHeight); } } - */ - - double heightShading = getHeightShading(y, heightW, heightN); - int lightValue = chunk.getLightValue(x, y + 1, z); - double lightShading = (double) lightValue / 15.0; - double shading = (heightShading + 1.0) * lightShading; - - // apply the shading - r = Math.min(Math.max(0.0, r * shading), 1.0); - g = Math.min(Math.max(0.0, g * shading), 1.0); - b = Math.min(Math.max(0.0, b * shading), 1.0); - - // now we have our final RGB values as doubles, convert to a packed ARGB - // pixel. - return ((y & 0xff) << 24) | ((((int) (r * 255.0)) & 0xff) << 16) - | ((((int) (g * 255.0)) & 0xff) << 8) - | ((((int) (b * 255.0)) & 0xff)); - } - - static int getPixelHeightN(int[] pixels, int offset, int scanSize) { - return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) - : -1; - } - - static int getPixelHeightW(int[] pixels, int offset, int scanSize) { - return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) - : -1; - } - - public static void renderSurface(BlockColours bc, IChunk chunk, - int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) { - int chunkMaxY = chunk.getMaxY(); - for (int z = 0; z < MwChunk.SIZE; z++) { - for (int x = 0; x < MwChunk.SIZE; x++) { - // for the nether dimension search for the first non-opaque - // block below the ceiling. - // cannot use y = chunkMaxY as the nether sometimes spawns - // mushrooms above the ceiling height. this fixes the - // rectangular grey areas (ceiling bedrock) on the nether map. - int y; - if (dimensionHasCeiling) { - for (y = 127; y >= 0; y--) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - - if (bc.getColour(blockAndMeta) == -8650628) { - alpha = 0; - } - - if (alpha != 0xff) { - break; - } - } - } else { - y = chunkMaxY - 1; - } - - int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour(bc, chunk, x, y, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize)); - } - } - } - - public static void renderUnderground(BlockColours bc, IChunk chunk, - int[] pixels, int offset, int scanSize, int startY, byte[] mask) { - startY = Math.min(Math.max(0, startY), 255); - for (int z = 0; z < MwChunk.SIZE; z++) { - for (int x = 0; x < MwChunk.SIZE; x++) { - - // only process columns where the mask bit is set. - // process all columns if mask is null. - if ((mask != null) && ((mask[(z * 16) + x]) != FLAG_NON_OPAQUE)) { - continue; - } - - // get the last non transparent block before the first opaque - // block searching - // towards the sky from startY - int lastNonTransparentY = startY; - for (int y = startY; y < chunk.getMaxY(); y++) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - - if (bc.getColour(blockAndMeta) == -8650628) { - alpha = 0; - } - - if (alpha == 0xff) { - break; - } - if (alpha > 0) { - lastNonTransparentY = y; - } - } - - int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour(bc, chunk, x, - lastNonTransparentY, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize)); - } - } - } -} +package mapwriter.region; + +import mapwriter.config.Config; + +public class ChunkRender +{ + + public static final byte FLAG_UNPROCESSED = 0; + public static final byte FLAG_NON_OPAQUE = 1; + public static final byte FLAG_OPAQUE = 2; + + // values that change how height shading algorithm works + public static final double brightenExponent = 0.35; + public static final double darkenExponent = 0.35; + public static final double brightenAmplitude = 0.7; + public static final double darkenAmplitude = 1.4; + + // get the height shading of a pixel. + // requires the pixel to the west and the pixel to the north to have their + // heights stored in the alpha channel to work. + // the "height" of a pixel is the y value of the first opaque block in + // the block column that created the pixel. + // height values of 0 and 255 are ignored as these are used as the clear + // values for pixels. + public static double getHeightShading(int height, int heightW, int heightN) + { + int samples = 0; + int heightDiff = 0; + + if ((heightW > 0) && (heightW < 255)) + { + heightDiff += height - heightW; + samples++; + } + + if ((heightN > 0) && (heightN < 255)) + { + heightDiff += height - heightN; + samples++; + } + + double heightDiffFactor = 0.0; + if (samples > 0) + { + heightDiffFactor = (double) heightDiff / ((double) samples); + } + + // emphasize small differences in height, but as the difference in + // height increases, + // don't increase so much + if (Config.moreRealisticMap) + { + return Math.atan(heightDiffFactor) * 0.3; + } + + return (heightDiffFactor >= 0.0) ? Math.pow(heightDiffFactor * (1 / 255.0), brightenExponent) * brightenAmplitude : -Math.pow(-(heightDiffFactor * (1 / 255.0)), darkenExponent) * darkenAmplitude; + } + + // calculate the colour of a pixel by alpha blending the colour of each + // block + // in a column until an opaque block is reached. + // y is topmost block height to start rendering at. + // for maps without a ceiling y is simply the height of the highest block in + // that chunk. + // for maps with a ceiling y is the height of the first non opaque block + // starting from + // the ceiling. + // + // for every block in the column starting from the highest: + // - get the block colour + // - get the biome shading + // - extract colour components as doubles in the range [0.0, 1.0] + // - the shaded block colour is simply the block colour multiplied + // by the biome shading for each component + // - this shaded block colour is alpha blended with the running + // colour for this column + // + // so the final map colour is an alpha blended stack of all the + // individual shaded block colours in the sequence [yStart .. yEnd] + // + // note that the "front to back" alpha blending algorithm is used + // rather than the more common "back to front". + // + public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, int z, int heightW, int heightN) + { + double a = 1.0; + double r = 0.0; + double g = 0.0; + double b = 0.0; + for (; y > 0; y--) + { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + int c1 = bc.getColour(blockAndMeta); + int alpha = (c1 >> 24) & 0xff; + + // this is the color that gets returned for air, so set aplha to 0 + // so the game continues to the next block in the colum + if (c1 == -8650628) + { + alpha = 0; + } + + // no need to process block if it is transparent + if (alpha > 0) + { + int biome = chunk.getBiome(x, z); + int c2 = bc.getBiomeColour(blockAndMeta, biome); + + // extract colour components as normalized doubles + double c1A = (alpha) / 255.0; + double c1R = ((c1 >> 16) & 0xff) / 255.0; + double c1G = ((c1 >> 8) & 0xff) / 255.0; + double c1B = ((c1 >> 0) & 0xff) / 255.0; + + // c2A is implicitly 1.0 (opaque) + double c2R = ((c2 >> 16) & 0xff) / 255.0; + double c2G = ((c2 >> 8) & 0xff) / 255.0; + double c2B = ((c2 >> 0) & 0xff) / 255.0; + + // alpha blend and multiply + r = r + (a * c1A * c1R * c2R); + g = g + (a * c1A * c1G * c2G); + b = b + (a * c1A * c1B * c2B); + a = a * (1.0 - c1A); + } + // break when an opaque block is encountered + if (alpha == 255) + { + break; + } + } + + /* + * // darken blocks depending on how far away they are from this depth + * slice if (depth != 0) { int bottomOfSlice = maxHeight - ((depth + 1) + * * maxHeight / Mw.HEIGHT_LEVELS) - 1; if (yRange[0] < bottomOfSlice) { + * shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / + * (double) maxHeight); } } + */ + + double heightShading = getHeightShading(y, heightW, heightN); + int lightValue = chunk.getLightValue(x, y + 1, z); + double lightShading = lightValue / 15.0; + double shading = (heightShading + 1.0) * lightShading; + + // apply the shading + r = Math.min(Math.max(0.0, r * shading), 1.0); + g = Math.min(Math.max(0.0, g * shading), 1.0); + b = Math.min(Math.max(0.0, b * shading), 1.0); + + // now we have our final RGB values as doubles, convert to a packed ARGB + // pixel. + return ((y & 0xff) << 24) | ((((int) (r * 255.0)) & 0xff) << 16) | ((((int) (g * 255.0)) & 0xff) << 8) | ((((int) (b * 255.0)) & 0xff)); + } + + static int getPixelHeightN(int[] pixels, int offset, int scanSize) + { + return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) : -1; + } + + static int getPixelHeightW(int[] pixels, int offset, int scanSize) + { + return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) : -1; + } + + public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) + { + int chunkMaxY = chunk.getMaxY(); + for (int z = 0; z < MwChunk.SIZE; z++) + { + for (int x = 0; x < MwChunk.SIZE; x++) + { + // for the nether dimension search for the first non-opaque + // block below the ceiling. + // cannot use y = chunkMaxY as the nether sometimes spawns + // mushrooms above the ceiling height. this fixes the + // rectangular grey areas (ceiling bedrock) on the nether map. + int y; + if (dimensionHasCeiling) + { + for (y = 127; y >= 0; y--) + { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + + if (bc.getColour(blockAndMeta) == -8650628) + { + alpha = 0; + } + + if (alpha != 0xff) + { + break; + } + } + } + else + { + y = chunkMaxY - 1; + } + + int pixelOffset = offset + (z * scanSize) + x; + pixels[pixelOffset] = getColumnColour(bc, chunk, x, y, z, getPixelHeightW(pixels, pixelOffset, scanSize), getPixelHeightN(pixels, pixelOffset, scanSize)); + } + } + } + + public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, int startY, byte[] mask) + { + startY = Math.min(Math.max(0, startY), 255); + for (int z = 0; z < MwChunk.SIZE; z++) + { + for (int x = 0; x < MwChunk.SIZE; x++) + { + + // only process columns where the mask bit is set. + // process all columns if mask is null. + if ((mask != null) && ((mask[(z * 16) + x]) != FLAG_NON_OPAQUE)) + { + continue; + } + + // get the last non transparent block before the first opaque + // block searching + // towards the sky from startY + int lastNonTransparentY = startY; + for (int y = startY; y < chunk.getMaxY(); y++) + { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + + if (bc.getColour(blockAndMeta) == -8650628) + { + alpha = 0; + } + + if (alpha == 0xff) + { + break; + } + if (alpha > 0) + { + lastNonTransparentY = y; + } + } + + int pixelOffset = offset + (z * scanSize) + x; + pixels[pixelOffset] = getColumnColour(bc, chunk, x, lastNonTransparentY, z, getPixelHeightW(pixels, pixelOffset, scanSize), getPixelHeightN(pixels, pixelOffset, scanSize)); + } + } + } +} diff --git a/src/main/java/mapwriter/region/IChunk.java b/src/main/java/mapwriter/region/IChunk.java index f85bf4b1..c59aa7fa 100644 --- a/src/main/java/mapwriter/region/IChunk.java +++ b/src/main/java/mapwriter/region/IChunk.java @@ -1,8 +1,12 @@ package mapwriter.region; -public interface IChunk { +public interface IChunk +{ public int getBlockAndMetadata(int x, int y, int z); + public int getBiome(int x, int z); + public int getLightValue(int x, int y, int z); + public int getMaxY(); } diff --git a/src/main/java/mapwriter/region/MergeToImage.java b/src/main/java/mapwriter/region/MergeToImage.java index f4634498..a0430ffd 100644 --- a/src/main/java/mapwriter/region/MergeToImage.java +++ b/src/main/java/mapwriter/region/MergeToImage.java @@ -1,94 +1,105 @@ -package mapwriter.region; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; - -import javax.imageio.ImageIO; - -import mapwriter.util.Logging; - -public class MergeToImage { - public static final int MAX_WIDTH = 8192; - public static final int MAX_HEIGHT = 8192; - - public static BufferedImage mergeRegions(RegionManager regionManager, int x, int z, int w, int h, int dimension) { - // create the image and graphics context - // this is the most likely place to run out of memory - BufferedImage mergedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); - - // copy region PNGs to the image - for (int zi = 0; zi < h; zi += Region.SIZE) { - for (int xi = 0; xi < w; xi += Region.SIZE) { - //MwUtil.log("merging region (%d,%d)", rX << Mw.REGION_SHIFT, rZ << Mw.REGION_SHIFT); - - // get region pixels - Region region = regionManager.getRegion(x + xi, z + zi, 0, dimension); - int[] regionPixels = region.surfacePixels.getPixels(); - if (regionPixels != null) { - mergedImage.setRGB(xi, zi, Region.SIZE, Region.SIZE, regionPixels, 0, Region.SIZE); - } - } - } - - return mergedImage; - } - - public static boolean writeImage(BufferedImage img, File f) { - boolean error = true; - try { - ImageIO.write(img, "png", f); - error = false; - } catch (IOException e) { - } - return error; - } - - public static int merge(RegionManager regionManager, int xCentre, int zCentre, int w, int h, int dimension, File dir, String basename) { - - // round up to nearest 512 block boundary - w = ((w + Region.SIZE - 1) & Region.MASK); - h = ((h + Region.SIZE - 1) & Region.MASK); - - // clamp to an integer between 512 and 8192 inclusive - w = Math.max(Region.SIZE, w); - h = Math.max(Region.SIZE, h); - - int xMin = xCentre - (w / 2); - int zMin = zCentre - (h / 2); - - // round to nearest region boundary - xMin = Math.round(((float) xMin) / ((float) Region.SIZE)) * Region.SIZE; - zMin = Math.round(((float) zMin) / ((float) Region.SIZE)) * Region.SIZE; - - int xMax = xMin + w; - int zMax = zMin + h; - - Logging.logInfo("merging area starting at (%d,%d), %dx%d blocks", - xMin, zMin, w, h); - - - int countZ = 0; - int count = 0; - for (int z = zMin; z < zMax; z += MAX_WIDTH) { - int imgH = Math.min(zMax - z, MAX_HEIGHT); - int countX = 0; - for (int x = xMin; x < xMax; x += MAX_WIDTH) { - int imgW = Math.min(xMax - x, MAX_WIDTH); - - String imgName = String.format("%s.%d.%d.png", basename, countX, countZ); - File f = new File(dir, imgName); - Logging.logInfo("merging regions to image %s", f); - - BufferedImage img = mergeRegions(regionManager, x, z, imgW, imgH, dimension); - writeImage(img, f); - - countX++; - count++; - } - countZ++; - } - - return count; - } -} +package mapwriter.region; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +import mapwriter.util.Logging; + +public class MergeToImage +{ + public static final int MAX_WIDTH = 8192; + public static final int MAX_HEIGHT = 8192; + + public static BufferedImage mergeRegions(RegionManager regionManager, int x, int z, int w, int h, int dimension) + { + // create the image and graphics context + // this is the most likely place to run out of memory + BufferedImage mergedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + + // copy region PNGs to the image + for (int zi = 0; zi < h; zi += Region.SIZE) + { + for (int xi = 0; xi < w; xi += Region.SIZE) + { + // MwUtil.log("merging region (%d,%d)", rX << Mw.REGION_SHIFT, + // rZ << Mw.REGION_SHIFT); + + // get region pixels + Region region = regionManager.getRegion(x + xi, z + zi, 0, dimension); + int[] regionPixels = region.surfacePixels.getPixels(); + if (regionPixels != null) + { + mergedImage.setRGB(xi, zi, Region.SIZE, Region.SIZE, regionPixels, 0, Region.SIZE); + } + } + } + + return mergedImage; + } + + public static boolean writeImage(BufferedImage img, File f) + { + boolean error = true; + try + { + ImageIO.write(img, "png", f); + error = false; + } + catch (IOException e) + { + } + return error; + } + + public static int merge(RegionManager regionManager, int xCentre, int zCentre, int w, int h, int dimension, File dir, String basename) + { + + // round up to nearest 512 block boundary + w = (((w + Region.SIZE) - 1) & Region.MASK); + h = (((h + Region.SIZE) - 1) & Region.MASK); + + // clamp to an integer between 512 and 8192 inclusive + w = Math.max(Region.SIZE, w); + h = Math.max(Region.SIZE, h); + + int xMin = xCentre - (w / 2); + int zMin = zCentre - (h / 2); + + // round to nearest region boundary + xMin = Math.round(((float) xMin) / ((float) Region.SIZE)) * Region.SIZE; + zMin = Math.round(((float) zMin) / ((float) Region.SIZE)) * Region.SIZE; + + int xMax = xMin + w; + int zMax = zMin + h; + + Logging.logInfo("merging area starting at (%d,%d), %dx%d blocks", xMin, zMin, w, h); + + int countZ = 0; + int count = 0; + for (int z = zMin; z < zMax; z += MAX_WIDTH) + { + int imgH = Math.min(zMax - z, MAX_HEIGHT); + int countX = 0; + for (int x = xMin; x < xMax; x += MAX_WIDTH) + { + int imgW = Math.min(xMax - x, MAX_WIDTH); + + String imgName = String.format("%s.%d.%d.png", basename, countX, countZ); + File f = new File(dir, imgName); + Logging.logInfo("merging regions to image %s", f); + + BufferedImage img = mergeRegions(regionManager, x, z, imgW, imgH, dimension); + writeImage(img, f); + + countX++; + count++; + } + countZ++; + } + + return count; + } +} diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 2c36b50b..1c29dbf0 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -1,439 +1,517 @@ -package mapwriter.region; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mapwriter.util.Logging; -import net.minecraft.block.Block; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockPos; -import net.minecraft.world.chunk.NibbleArray; -import net.minecraftforge.fml.common.FMLLog; - -import org.apache.logging.log4j.Level; - -public class MwChunk implements IChunk { - public static final int SIZE = 16; - - public final int x; - public final int z; - public final int dimension; - - char[][] dataArray = new char[16][]; - - public final byte[][] lightingArray; - public final Map tileentityMap; - - public final byte[] biomeArray; - - public final int maxY; - - public MwChunk(int x, int z, int dimension, char[][] data, - byte[][] lightingArray, byte[] biomeArray, - Map TileEntityMap) { - - this.x = x; - this.z = z; - this.dimension = dimension; - this.biomeArray = biomeArray; - this.lightingArray = lightingArray; - this.tileentityMap = TileEntityMap; - this.dataArray = data; - int maxY = 0; - for (int y = 0; y < 16; y++) { - if (data[y] != null) { - maxY = (y << 4) + 15; - } - } - this.maxY = maxY; - } - - public String toString() { - return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); - } - - // load from anvil file - public static MwChunk read(int x, int z, int dimension, - RegionFileCache regionFileCache) { - - byte[] biomeArray = null; - byte[][] lsbArray = new byte[16][]; - char[][] data = new char[16][]; - byte[][] lightingArray = new byte[16][]; - Map TileEntityMap = new HashMap(); - - DataInputStream dis = null; - RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, - dimension); - if (!regionFile.isOpen()) { - if (regionFile.exists()) { - regionFile.open(); - } - } - - if (regionFile.isOpen()) { - dis = regionFile.getChunkDataInputStream(x & 31, z & 31); - } - - if (dis != null) { - try { - - // chunk NBT structure: - // - // COMPOUND "" - // COMPOUND "level" - // INT "xPos" - // INT "zPos" - // LONG "LastUpdate" - // BYTE "TerrainPopulated" - // BYTE_ARRAY "Biomes" - // INT_ARRAY "HeightMap" - // LIST(COMPOUND) "Sections" - // BYTE "Y" - // BYTE_ARRAY "Blocks" - // BYTE_ARRAY "Add" - // BYTE_ARRAY "Data" - // BYTE_ARRAY "BlockLight" - // BYTE_ARRAY "SkyLight" - // END - // LIST(COMPOUND) "Entities" - // LIST(COMPOUND) "TileEntities" - // LIST(COMPOUND) "TileTicks" - // END - // END - NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); - NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); - - int xNbt = level.getInteger("xPos"); - int zNbt = level.getInteger("zPos"); - - if ((xNbt != x) || (zNbt != z)) { - Logging.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); - } - - NBTTagList sections = level.getTagList("Sections", 10); - - for (int k = 0; k < sections.tagCount(); ++k) { - NBTTagCompound section = sections.getCompoundTagAt(k); - int y = section.getByte("Y"); - lsbArray[y & 0xf] = section.getByteArray("Blocks"); - NibbleArray nibblearray = new NibbleArray( - section.getByteArray("Data")); - NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray( - section.getByteArray("Add")) : null; - - data[y & 0xf] = new char[lsbArray[y].length]; - - for (int l = 0; l < data[y & 0xf].length; ++l) { - int i1 = l & 15; - int j1 = l >> 8 & 15; - int k1 = l >> 4 & 15; - int l1 = nibblearray1 != null ? nibblearray1.get(i1, - j1, k1) : 0; - data[y & 0xf][l] = (char) (l1 << 12 - | (lsbArray[y][l] & 255) << 4 | nibblearray - .get(i1, j1, k1)); - } - } - - biomeArray = level.getByteArray("Biomes"); - - NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); - - if (nbttaglist2 != null) { - for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) { - NBTTagCompound nbttagcompound4 = nbttaglist2 - .getCompoundTagAt(i1); - TileEntity tileentity = TileEntity - .createAndLoadEntity(nbttagcompound4); - if (tileentity != null) { - TileEntityMap.put(tileentity.getPos(), tileentity); - } - } - } - - } catch (IOException e) { - Logging.logError("%s: could not read chunk (%d, %d) from region file\n",e, x, z); - } finally { - try { - dis.close(); - } catch (IOException e) { - Logging.logError("MwChunk.read: %s while closing input stream", e); - } - } - // this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, - // empty); - } else { - // this.log("MwChunk.read: chunk (%d, %d) input stream is null", - // this.x, this.z); - } - - return new MwChunk(x, z, dimension, data, lightingArray, biomeArray, - TileEntityMap); - } - - public boolean isEmpty() { - return (this.maxY <= 0); - } - - public int getBiome(int x, int z) { - return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) - | (x & 0xf)]) & 0xff - : 0; - } - - public int getLightValue(int x, int y, int z) { - // int yi = (y >> 4) & 0xf; - // int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - // int light = ((this.lightingArray != null) && (this.lightingArray[yi] - // != null)) ? this.lightingArray[yi][offset >> 1] : 15; - - // return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); - return 15; - } - - public int getMaxY() { - return this.maxY; - } - - private static java.lang.reflect.Method CarpenterMethod = null; - - public static void carpenterdata() { - try { - Class act = Class - .forName("com.carpentersblocks.tileentity.TEBase"); - CarpenterMethod = act.getMethod("getAttribute", byte.class); - } catch (SecurityException e) { - // ... - } catch (NoSuchMethodException e) { - // ... - } catch (ClassNotFoundException e) { - // - } - } - - private static java.lang.reflect.Method FMPMethodParts = null; - private static java.lang.reflect.Method FMPMethodMaterial = null; - - private static java.lang.reflect.Field FMPFieldBlock = null; - private static java.lang.reflect.Field FMPFieldMeta = null; - - public static void FMPdata() { - try { - Class act = Class.forName("codechicken.multipart.TileMultipart"); - FMPMethodParts = act.getMethod("jPartList"); - act = Class.forName("codechicken.microblock.Microblock"); - FMPMethodMaterial = act.getMethod("getIMaterial"); - - act = Class.forName("codechicken.microblock.BlockMicroMaterial"); - FMPFieldBlock = act.getDeclaredField("block"); - FMPFieldBlock.setAccessible(true); - - FMPFieldMeta = act.getDeclaredField("meta"); - FMPFieldMeta.setAccessible(true); - - } catch (SecurityException e) { - // ... - } catch (NoSuchMethodException e) { - // ... - } catch (ClassNotFoundException e) { - // - } catch (NoSuchFieldException e) { - // - } - } - - public int getBlockAndMetadata(int x, int y, int z) { - int yi = (y >> 4) & 0xf; - int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - int lsb = 0; - int msb = 0; - int meta = 0; - - BlockPos pos = new BlockPos(x, y, z); - - char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] - : 0; - - // check if the block has a tileentity if so use the blockdata in the - // tileentity - // (forgemultipart and carpenterblocks both save the block to be - // rendered in the tileentity map) - - if (this.tileentityMap.containsKey(pos)) { - TileEntity value = (TileEntity) this.tileentityMap - .get(pos); - int id = 0; - - // Get the Block from the carpenter TileEntity - if (CarpenterMethod != null) { - try { - ItemStack itemStack = (ItemStack) CarpenterMethod.invoke( - value, (byte) 6); - if (itemStack != null) { - ItemBlock itemBlock = (ItemBlock) itemStack.getItem(); - id = Block.getIdFromBlock(itemBlock.block); - meta = itemStack.getMetadata(); - } - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } - if (FMPMethodParts != null) { - try { - for (Object temp : (List) FMPMethodParts.invoke(value)) { - Object material = FMPMethodMaterial.invoke(temp); - Block block = (Block) FMPFieldBlock.get(material); - id = Block.getIdFromBlock(block); - meta = (Integer) FMPFieldMeta.get(material); - } - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } - if (id != 0) - { - lsb = (id & 255); - if (id > 255) { - msb = (id & 3840) >> 8; - } - else { - msb = 0; - } - data = (char) (((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); - } - } - - return (int) data; - } - - // changed to use the NBTTagCompound that minecraft uses. this makes the - // local way of saving anvill data the same as Minecraft world data - private NBTTagCompound writeChunkToNBT() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound.setTag("Level", nbttagcompound1); - - nbttagcompound1.setInteger("xPos", this.x); - nbttagcompound1.setInteger("zPos", this.z); - - NBTTagList nbttaglist = new NBTTagList(); - NBTTagCompound nbttagcompound2; - - for (int y = 0; y < this.dataArray.length; y++) { - if (this.dataArray[y] != null) { - byte[] abyte = new byte[this.dataArray[y].length]; - NibbleArray nibblearray = new NibbleArray(); - NibbleArray nibblearray1 = null; - - for (int k = 0; k < this.dataArray[y].length; ++k) { - char c0 = this.dataArray[y][k]; - int l = k & 15; - int i1 = k >> 8 & 15; - int j1 = k >> 4 & 15; - - if (c0 >> 12 != 0) { - if (nibblearray1 == null) { - nibblearray1 = new NibbleArray(); - } - - nibblearray1.set(l, i1, j1, c0 >> 12); - } - - abyte[k] = (byte) (c0 >> 4 & 255); - nibblearray.set(l, i1, j1, c0 & 15); - } - - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Y", (byte) y); - nbttagcompound2.setByteArray("Blocks", abyte); - - if (nibblearray1 != null) { - nbttagcompound2.setByteArray("Add", nibblearray1.getData()); - } - - nbttagcompound2.setByteArray("Data", nibblearray.getData()); - nbttaglist.appendTag(nbttagcompound2); - } - - nbttagcompound1.setTag("Sections", nbttaglist); - } - nbttagcompound1.setByteArray("Biomes", this.biomeArray); - - NBTTagList nbttaglist3 = new NBTTagList(); - - Iterator iterator1 = this.tileentityMap.values().iterator(); - - while (iterator1.hasNext()) { - TileEntity tileentity = (TileEntity) iterator1.next(); - nbttagcompound2 = new NBTTagCompound(); - try { - tileentity.writeToNBT(nbttagcompound2); - nbttaglist3.appendTag(nbttagcompound2); - } catch (Exception e) { - FMLLog.log( - Level.ERROR, - e, - "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", - tileentity.getClass().getName()); - } - } - nbttagcompound1.setTag("TileEntities", nbttaglist3); - - return nbttagcompound; - } - - public synchronized boolean write(RegionFileCache regionFileCache) { - boolean error = false; - RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, - this.z << 4, this.dimension); - if (!regionFile.isOpen()) { - error = regionFile.open(); - } - if (!error) { - DataOutputStream dos = regionFile.getChunkDataOutputStream( - this.x & 31, this.z & 31); - if (dos != null) { - // Nbt chunkNbt = this.getNbt(); - try { - // RegionManager.logInfo("writing chunk (%d, %d) to region file", - // this.x, this.z); - // chunkNbt.writeElement(dos); - // use minecraft build in save tool for saving the Anvil - // Data - CompressedStreamTools.write(writeChunkToNBT(), dos); - } catch (IOException e) { - Logging.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); - error = true; - } finally { - try { - dos.close(); - } catch (IOException e) { - Logging.logError( "%s while closing chunk data output stream", e); - } - } - } else { - Logging.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); - } - } else { - Logging.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); - } - - return error; - } -} +package mapwriter.region; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mapwriter.util.Logging; +import net.minecraft.block.Block; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.chunk.NibbleArray; +import net.minecraftforge.fml.common.FMLLog; + +import org.apache.logging.log4j.Level; + +public class MwChunk implements IChunk +{ + public static final int SIZE = 16; + + public final int x; + public final int z; + public final int dimension; + + char[][] dataArray = new char[16][]; + + public final byte[][] lightingArray; + public final Map tileentityMap; + + public final byte[] biomeArray; + + public final int maxY; + + public MwChunk(int x, int z, int dimension, char[][] data, byte[][] lightingArray, byte[] biomeArray, Map TileEntityMap) + { + + this.x = x; + this.z = z; + this.dimension = dimension; + this.biomeArray = biomeArray; + this.lightingArray = lightingArray; + this.tileentityMap = TileEntityMap; + this.dataArray = data; + int maxY = 0; + for (int y = 0; y < 16; y++) + { + if (data[y] != null) + { + maxY = (y << 4) + 15; + } + } + this.maxY = maxY; + } + + @Override + public String toString() + { + return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); + } + + // load from anvil file + public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) + { + + byte[] biomeArray = null; + byte[][] lsbArray = new byte[16][]; + char[][] data = new char[16][]; + byte[][] lightingArray = new byte[16][]; + Map TileEntityMap = new HashMap(); + + DataInputStream dis = null; + RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); + if (!regionFile.isOpen()) + { + if (regionFile.exists()) + { + regionFile.open(); + } + } + + if (regionFile.isOpen()) + { + dis = regionFile.getChunkDataInputStream(x & 31, z & 31); + } + + if (dis != null) + { + try + { + + // chunk NBT structure: + // + // COMPOUND "" + // COMPOUND "level" + // INT "xPos" + // INT "zPos" + // LONG "LastUpdate" + // BYTE "TerrainPopulated" + // BYTE_ARRAY "Biomes" + // INT_ARRAY "HeightMap" + // LIST(COMPOUND) "Sections" + // BYTE "Y" + // BYTE_ARRAY "Blocks" + // BYTE_ARRAY "Add" + // BYTE_ARRAY "Data" + // BYTE_ARRAY "BlockLight" + // BYTE_ARRAY "SkyLight" + // END + // LIST(COMPOUND) "Entities" + // LIST(COMPOUND) "TileEntities" + // LIST(COMPOUND) "TileTicks" + // END + // END + NBTTagCompound nbttagcompound = CompressedStreamTools.read(dis); + NBTTagCompound level = nbttagcompound.getCompoundTag("Level"); + + int xNbt = level.getInteger("xPos"); + int zNbt = level.getInteger("zPos"); + + if ((xNbt != x) || (zNbt != z)) + { + Logging.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); + } + + NBTTagList sections = level.getTagList("Sections", 10); + + for (int k = 0; k < sections.tagCount(); ++k) + { + NBTTagCompound section = sections.getCompoundTagAt(k); + int y = section.getByte("Y"); + lsbArray[y & 0xf] = section.getByteArray("Blocks"); + NibbleArray nibblearray = new NibbleArray(section.getByteArray("Data")); + NibbleArray nibblearray1 = section.hasKey("Add", 7) ? new NibbleArray(section.getByteArray("Add")) : null; + + data[y & 0xf] = new char[lsbArray[y].length]; + + for (int l = 0; l < data[y & 0xf].length; ++l) + { + int i1 = l & 15; + int j1 = (l >> 8) & 15; + int k1 = (l >> 4) & 15; + int l1 = nibblearray1 != null ? nibblearray1.get(i1, j1, k1) : 0; + data[y & 0xf][l] = (char) ((l1 << 12) | ((lsbArray[y][l] & 255) << 4) | nibblearray.get(i1, j1, k1)); + } + } + + biomeArray = level.getByteArray("Biomes"); + + NBTTagList nbttaglist2 = level.getTagList("TileEntities", 10); + + if (nbttaglist2 != null) + { + for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) + { + NBTTagCompound nbttagcompound4 = nbttaglist2.getCompoundTagAt(i1); + TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4); + if (tileentity != null) + { + TileEntityMap.put(tileentity.getPos(), tileentity); + } + } + } + + } + catch (IOException e) + { + Logging.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); + } + finally + { + try + { + dis.close(); + } + catch (IOException e) + { + Logging.logError("MwChunk.read: %s while closing input stream", e); + } + } + // this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, + // empty); + } + else + { + // this.log("MwChunk.read: chunk (%d, %d) input stream is null", + // this.x, this.z); + } + + return new MwChunk(x, z, dimension, data, lightingArray, biomeArray, TileEntityMap); + } + + public boolean isEmpty() + { + return (this.maxY <= 0); + } + + @Override + public int getBiome(int x, int z) + { + return (this.biomeArray != null) ? (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; + } + + @Override + public int getLightValue(int x, int y, int z) + { + // int yi = (y >> 4) & 0xf; + // int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + // int light = ((this.lightingArray != null) && (this.lightingArray[yi] + // != null)) ? this.lightingArray[yi][offset >> 1] : 15; + + // return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); + return 15; + } + + @Override + public int getMaxY() + { + return this.maxY; + } + + private static java.lang.reflect.Method CarpenterMethod = null; + + public static void carpenterdata() + { + try + { + Class act = Class.forName("com.carpentersblocks.tileentity.TEBase"); + CarpenterMethod = act.getMethod("getAttribute", byte.class); + } + catch (SecurityException e) + { + // ... + } + catch (NoSuchMethodException e) + { + // ... + } + catch (ClassNotFoundException e) + { + // + } + } + + private static java.lang.reflect.Method FMPMethodParts = null; + private static java.lang.reflect.Method FMPMethodMaterial = null; + + private static java.lang.reflect.Field FMPFieldBlock = null; + private static java.lang.reflect.Field FMPFieldMeta = null; + + public static void FMPdata() + { + try + { + Class act = Class.forName("codechicken.multipart.TileMultipart"); + FMPMethodParts = act.getMethod("jPartList"); + act = Class.forName("codechicken.microblock.Microblock"); + FMPMethodMaterial = act.getMethod("getIMaterial"); + + act = Class.forName("codechicken.microblock.BlockMicroMaterial"); + FMPFieldBlock = act.getDeclaredField("block"); + FMPFieldBlock.setAccessible(true); + + FMPFieldMeta = act.getDeclaredField("meta"); + FMPFieldMeta.setAccessible(true); + + } + catch (SecurityException e) + { + // ... + } + catch (NoSuchMethodException e) + { + // ... + } + catch (ClassNotFoundException e) + { + // + } + catch (NoSuchFieldException e) + { + // + } + } + + @Override + public int getBlockAndMetadata(int x, int y, int z) + { + int yi = (y >> 4) & 0xf; + int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + int lsb = 0; + int msb = 0; + int meta = 0; + + BlockPos pos = new BlockPos(x, y, z); + + char data = ((this.dataArray != null) && (this.dataArray[yi] != null) && (this.dataArray[yi].length != 0)) ? this.dataArray[yi][offset] : 0; + + // check if the block has a tileentity if so use the blockdata in the + // tileentity + // (forgemultipart and carpenterblocks both save the block to be + // rendered in the tileentity map) + + if (this.tileentityMap.containsKey(pos)) + { + TileEntity value = this.tileentityMap.get(pos); + int id = 0; + + // Get the Block from the carpenter TileEntity + if (CarpenterMethod != null) + { + try + { + ItemStack itemStack = (ItemStack) CarpenterMethod.invoke(value, (byte) 6); + if (itemStack != null) + { + ItemBlock itemBlock = (ItemBlock) itemStack.getItem(); + id = Block.getIdFromBlock(itemBlock.block); + meta = itemStack.getMetadata(); + } + } + catch (IllegalArgumentException e) + { + } + catch (IllegalAccessException e) + { + } + catch (InvocationTargetException e) + { + } + } + if (FMPMethodParts != null) + { + try + { + for (Object temp : (List) FMPMethodParts.invoke(value)) + { + Object material = FMPMethodMaterial.invoke(temp); + Block block = (Block) FMPFieldBlock.get(material); + id = Block.getIdFromBlock(block); + meta = (Integer) FMPFieldMeta.get(material); + } + } + catch (IllegalArgumentException e) + { + } + catch (IllegalAccessException e) + { + } + catch (InvocationTargetException e) + { + } + } + if (id != 0) + { + lsb = (id & 255); + if (id > 255) + { + msb = (id & 3840) >> 8; + } + else + { + msb = 0; + } + data = (char) (((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f)); + } + } + + return data; + } + + // changed to use the NBTTagCompound that minecraft uses. this makes the + // local way of saving anvill data the same as Minecraft world data + private NBTTagCompound writeChunkToNBT() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound.setTag("Level", nbttagcompound1); + + nbttagcompound1.setInteger("xPos", this.x); + nbttagcompound1.setInteger("zPos", this.z); + + NBTTagList nbttaglist = new NBTTagList(); + NBTTagCompound nbttagcompound2; + + for (int y = 0; y < this.dataArray.length; y++) + { + if (this.dataArray[y] != null) + { + byte[] abyte = new byte[this.dataArray[y].length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < this.dataArray[y].length; ++k) + { + char c0 = this.dataArray[y][k]; + int l = k & 15; + int i1 = (k >> 8) & 15; + int j1 = (k >> 4) & 15; + + if ((c0 >> 12) != 0) + { + if (nibblearray1 == null) + { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte) ((c0 >> 4) & 255); + nibblearray.set(l, i1, j1, c0 & 15); + } + + nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Y", (byte) y); + nbttagcompound2.setByteArray("Blocks", abyte); + + if (nibblearray1 != null) + { + nbttagcompound2.setByteArray("Add", nibblearray1.getData()); + } + + nbttagcompound2.setByteArray("Data", nibblearray.getData()); + nbttaglist.appendTag(nbttagcompound2); + } + + nbttagcompound1.setTag("Sections", nbttaglist); + } + nbttagcompound1.setByteArray("Biomes", this.biomeArray); + + NBTTagList nbttaglist3 = new NBTTagList(); + + Iterator iterator1 = this.tileentityMap.values().iterator(); + + while (iterator1.hasNext()) + { + TileEntity tileentity = iterator1.next(); + nbttagcompound2 = new NBTTagCompound(); + try + { + tileentity.writeToNBT(nbttagcompound2); + nbttaglist3.appendTag(nbttagcompound2); + } + catch (Exception e) + { + FMLLog.log(Level.ERROR, e, "A TileEntity type %s has throw an exception trying to write state. It will not persist. Report this to the mod author", tileentity.getClass().getName()); + } + } + nbttagcompound1.setTag("TileEntities", nbttaglist3); + + return nbttagcompound; + } + + public synchronized boolean write(RegionFileCache regionFileCache) + { + boolean error = false; + RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); + if (!regionFile.isOpen()) + { + error = regionFile.open(); + } + if (!error) + { + DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); + if (dos != null) + { + // Nbt chunkNbt = this.getNbt(); + try + { + // RegionManager.logInfo("writing chunk (%d, %d) to region file", + // this.x, this.z); + // chunkNbt.writeElement(dos); + // use minecraft build in save tool for saving the Anvil + // Data + CompressedStreamTools.write(this.writeChunkToNBT(), dos); + } + catch (IOException e) + { + Logging.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); + error = true; + } + finally + { + try + { + dos.close(); + } + catch (IOException e) + { + Logging.logError("%s while closing chunk data output stream", e); + } + } + } + else + { + Logging.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); + } + } + else + { + Logging.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/region/Region.java b/src/main/java/mapwriter/region/Region.java index 29e34916..f5f264f4 100644 --- a/src/main/java/mapwriter/region/Region.java +++ b/src/main/java/mapwriter/region/Region.java @@ -3,135 +3,144 @@ import java.io.File; /* - MwRegion class - Represents a 32x32 chunk area (512x512 blocks). -*/ -public class Region { - + * MwRegion class Represents a 32x32 chunk area (512x512 blocks). + */ +public class Region +{ + public RegionManager regionManager; - + public static final int SHIFT = 9; public static final int SIZE = 1 << SHIFT; public static final int MASK = -SIZE; - + public final int x; public final int z; public final int dimension; public final int zoomLevel; public final Long key; public final int size; - + public SurfacePixels surfacePixels; - - public Region(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { - + + public Region(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) + { + this.regionManager = regionManager; - + this.zoomLevel = Math.min(Math.max(0, zoomLevel), regionManager.maxZoom); this.dimension = dimension; this.size = Region.SIZE << zoomLevel; this.x = x & (-this.size); this.z = z & (-this.size); - + this.key = getKey(this.x, this.z, this.zoomLevel, this.dimension); - + File surfaceImageFile = this.getImageFile(); this.surfacePixels = new SurfacePixels(this, surfaceImageFile); } - - public void close() { + + public void close() + { this.surfacePixels.close(); } - - public void clear() { + + public void clear() + { this.surfacePixels.clear(); } - - public String toString() { + + @Override + public String toString() + { return String.format("(%d,%d) z%d dim%d", this.x, this.z, this.zoomLevel, this.dimension); } - - private static File addDimensionDirToPath(File dir, int dimension) { - if (dimension != 0) { + + private static File addDimensionDirToPath(File dir, int dimension) + { + if (dimension != 0) + { dir = new File(dir, "DIM" + dimension); } return dir; } - - public File getImageFile() { + + public File getImageFile() + { File dimDir = addDimensionDirToPath(this.regionManager.imageDir, this.dimension); File zoomDir = new File(dimDir, "z" + this.zoomLevel); - + zoomDir.mkdirs(); - - String filename = String.format("%d.%d.png", - this.x >> (Region.SHIFT + this.zoomLevel), - this.z >> (Region.SHIFT + this.zoomLevel) - ); - + + String filename = String.format("%d.%d.png", this.x >> (Region.SHIFT + this.zoomLevel), this.z >> (Region.SHIFT + this.zoomLevel)); + return new File(zoomDir, filename); } - - public boolean equals(int x, int z, int zoomLevel, int dimension) { + + public boolean equals(int x, int z, int zoomLevel, int dimension) + { x &= -this.size; z &= -this.size; return (this.x == x) && (this.z == z) && (this.zoomLevel == zoomLevel) && (this.dimension == dimension); } - + @Override - public boolean equals(Object o) { + public boolean equals(Object o) + { boolean equal = false; - if (o != null) { - if (o instanceof Region) { + if (o != null) + { + if (o instanceof Region) + { Region region = (Region) o; equal = this.equals(region.x, region.z, region.zoomLevel, region.dimension); } } return equal; } - - public static Long getKey(int x, int z, int zoomLevel, int dimension) { + + public static Long getKey(int x, int z, int zoomLevel, int dimension) + { x = (x >> (Region.SHIFT + zoomLevel)) & 0xffff; z = (z >> (Region.SHIFT + zoomLevel)) & 0xffff; zoomLevel = zoomLevel & 0xff; dimension = dimension & 0xff; - return Long.valueOf( - (((long) dimension) << 40) | - (((long) zoomLevel) << 32) | - (((long) z) << 16) | - ((long) x)); - } - - public int getPixelOffset(int x, int z) { - return (((z >> this.zoomLevel) & (Region.SIZE - 1)) << Region.SHIFT) + - ((x >> this.zoomLevel) & (Region.SIZE - 1)); - } - - public int[] getPixels() { + return Long.valueOf((((long) dimension) << 40) | (((long) zoomLevel) << 32) | (((long) z) << 16) | (x)); + } + + public int getPixelOffset(int x, int z) + { + return (((z >> this.zoomLevel) & (Region.SIZE - 1)) << Region.SHIFT) + ((x >> this.zoomLevel) & (Region.SIZE - 1)); + } + + public int[] getPixels() + { return this.surfacePixels.getPixels(); } - - public boolean isAreaWithin(int x, int z, int w, int h, int dimension) { - return (x >= this.x) && (z >= this.z) && - ((x + w) <= (this.x + this.size)) && ((z + h) <= (this.z + this.size)) && - (dimension == this.dimension); + + public boolean isAreaWithin(int x, int z, int w, int h, int dimension) + { + return (x >= this.x) && (z >= this.z) && ((x + w) <= (this.x + this.size)) && ((z + h) <= (this.z + this.size)) && (dimension == this.dimension); } - + // scale an area of pixels by half in this region and write them // to the pixels of the next zoom level region. // x, z, w, h, in world block coordinates // returns the region the scaled pixels were written to, or null // on failure. - public Region updateNextZoomLevel(int x, int z, int w, int h) { + public Region updateNextZoomLevel(int x, int z, int w, int h) + { int[] srcPixels = this.surfacePixels.getPixels(); Region dstRegion = null; - if (srcPixels != null) { - int dstZoomLevel = this.zoomLevel + 1; - if (dstZoomLevel <= this.regionManager.maxZoom) { + if (srcPixels != null) + { + int dstZoomLevel = this.zoomLevel + 1; + if (dstZoomLevel <= this.regionManager.maxZoom) + { dstRegion = this.regionManager.getRegion(x, z, dstZoomLevel, this.dimension); int dstW = Math.max(1, (w >> dstRegion.zoomLevel)); int dstH = Math.max(1, (h >> dstRegion.zoomLevel)); - + // AND srcX and srcZ by -2 (0xfffffffe) to make sure that // they are always even. This prevents out of bounds exceptions // at higher zoom levels. @@ -139,30 +148,35 @@ public Region updateNextZoomLevel(int x, int z, int w, int h) { int srcZ = (z >> this.zoomLevel) & (Region.SIZE - 1) & (-2); int dstX = (x >> dstRegion.zoomLevel) & (Region.SIZE - 1); int dstZ = (z >> dstRegion.zoomLevel) & (Region.SIZE - 1); - + dstRegion.surfacePixels.updateScaled(srcPixels, srcX, srcZ, dstX, dstZ, dstW, dstH); } } - + return dstRegion; } - + // update all higher zoom level regions that this region // lies within - public void updateZoomLevels(int x, int z, int w, int h) { + public void updateZoomLevels(int x, int z, int w, int h) + { Region nextRegion = this; - while (nextRegion != null) { + while (nextRegion != null) + { nextRegion = nextRegion.updateNextZoomLevel(x, z, w, h); } } - + // update this entire region in the next zoom level - public void updateZoomLevels() { + public void updateZoomLevels() + { this.updateZoomLevels(this.x, this.z, this.size, this.size); } - - public void updateChunk(MwChunk chunk) { - if (this.zoomLevel == 0) { + + public void updateChunk(MwChunk chunk) + { + if (this.zoomLevel == 0) + { this.surfacePixels.updateChunk(chunk); } } diff --git a/src/main/java/mapwriter/region/RegionFile.java b/src/main/java/mapwriter/region/RegionFile.java index a06119bc..3c6a338c 100644 --- a/src/main/java/mapwriter/region/RegionFile.java +++ b/src/main/java/mapwriter/region/RegionFile.java @@ -1,374 +1,474 @@ -package mapwriter.region; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -import mapwriter.util.Logging; - -/* -Anvil region file reader/writer implementation. -This code is very similar to RegionFile and RegionFileChunkBuffer from Minecraft. -Not sure if it would have been better just to use the Minecraft code. -*/ - -public class RegionFile { - - private final File file; - private int lengthInSectors = 0; - private RandomAccessFile fin = null; - - private Section[] chunkSectionsArray = new Section[4096]; - private int[] timestampArray = new int[4096]; - private List filledSectorArray = null; - - private class Section { - final int startSector; - final int length; - Section(int startSector, int length) { - this.startSector = startSector; - this.length = length; - } - Section(int sectorAndSize) { - this((sectorAndSize >> 8) & 0xffffff, sectorAndSize & 0xff); - } - int getSectorAndSize() { - return (this.startSector << 8) | (this.length & 0xff); - } - } - - public RegionFile(File file) { - this.file = file; - } - - public String toString() { - return String.format("%s", this.file); - } - - public boolean exists() { - return this.file.isFile(); - } - - public boolean isOpen() { - return (this.fin != null); - } - - // set the corresponding bits in filledSectorArray to 'filled' - // for 'count' sectors, starting at 'firstSector'. - private void setFilledSectorArray(Section section, boolean filled) { - int endSector = section.startSector + section.length; - int sectorsToAppend = endSector + 1 - this.filledSectorArray.size(); - for (int i = 0; i < sectorsToAppend; i++) { - this.filledSectorArray.add(Boolean.valueOf(false)); - } - for (int i = section.startSector; i < endSector; i++) { - if (filled && this.filledSectorArray.get(i)) { - Logging.logError("sector %d already filled, possible chunk overlap", i); - } - this.filledSectorArray.set(i, Boolean.valueOf(filled)); - } - } - - private boolean checkSectionOverlaps(Section section) { - // get end sector, limiting to length of the filled sector array as all sectors past the - // end of the file are assumed free. - int endSector = Math.min(section.startSector + section.length, this.filledSectorArray.size()); - boolean overlaps = false; - for (int i = section.startSector; i < endSector; i++) { - if (this.filledSectorArray.get(i)) { - overlaps = true; - } - } - return overlaps; - } - - private Section getFreeSection(int requiredLength) { - int start = 0; - int length = 0; - int closestStart = 0; - int closestLength = Integer.MAX_VALUE; - // start at 2 to skip headers - int i; - for (i = 2; i < this.filledSectorArray.size(); i++) { - if (this.filledSectorArray.get(i)) { - // sector filled - // if the length of the empty block we found is greater than or - // equal to the required length, and is closer to the required - // length than the previous found length, then set this as the - // new closest length. - // the idea is to use an empty block of exactly the required - // length, rather than one that is larger. - if ((length >= requiredLength) && (length < closestLength)) { - closestLength = length; - closestStart = start; - // if we find an empty block of exactly the correct length - // then exit the loop. - if (closestLength == requiredLength) { - break; - } - } - length = 0; - } else { - // sector empty - if (length == 0) { - start = i; - } - length++; - } - } - - if (closestStart <= 0) { - // append to end of file - closestStart = i; - } - - return new Section(closestStart, requiredLength); - } - - public void printInfo() { - int freeCount = 0; - int filledCount = 0; - // start at 2 to skip headers - for (int i = 2; i < this.filledSectorArray.size(); i++) { - if (this.filledSectorArray.get(i)) { - filledCount++; - } else { - freeCount++; - } - } - Logging.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); - - String s = ""; - int i; - for (i = 0; i < this.filledSectorArray.size(); i++) { - if ((i & 31) == 0) { - s = String.format("%04x:", i); - } - s += this.filledSectorArray.get(i) ? '1' : '0'; - if ((i & 31) == 31) { - Logging.logInfo("%s", s); - } - } - if ((i & 31) != 31) { - Logging.logInfo("%s", s); - } - } - - private Section getChunkSection(int x, int z) { - return this.chunkSectionsArray[((z & 31) << 5) | (x & 31)]; - } - - private void updateChunkSection(int x, int z, Section newSection) throws IOException { - int chunkIndex = ((z & 31) << 5) | (x & 31); - this.fin.seek(chunkIndex * 4); - if ((newSection != null) && (newSection.length > 0)) { - this.fin.writeInt(newSection.getSectorAndSize()); - } else { - this.fin.writeInt(0); - } - - this.chunkSectionsArray[chunkIndex] = newSection; - } - - public boolean open() { - File dir = this.file.getParentFile(); - if (dir.exists()) { - if (!dir.isDirectory()) { - Logging.logError("path %s exists and is not a directory", dir); - return true; - } - } else { - if (!dir.mkdirs()) { - Logging.logError("could not create directory %s", dir); - return true; - } - } - try { - this.fin = new RandomAccessFile(this.file, "rw"); - - // seek to start - this.fin.seek(0); - - this.lengthInSectors = (int) ((this.fin.length() + 4095L) / 4096L); - - this.filledSectorArray = new ArrayList(); - - Arrays.fill(this.chunkSectionsArray, null); - Arrays.fill(this.timestampArray, 0); - - if (this.lengthInSectors < 3) { - // no chunk data - // fill chunk and timestamp tables with 0's - for (int i = 0; i < 2048; i++) { - this.fin.writeInt(0); - } - } else { - // add a section for each chunk - for (int i = 0; i < 1024; i++) { - Section section = new Section(this.fin.readInt()); - if (section.length > 0) { - // make sure chunk does not overlap another - if (!checkSectionOverlaps(section)) { - this.chunkSectionsArray[i] = section; - this.setFilledSectorArray(section, true); - } else { - Logging.logError("chunk %d overlaps another chunk, file may be corrupt", i); - } - } - } - for (int i = 0; i < 1024; i++) { - this.timestampArray[i] = this.fin.readInt(); - } - } - - //this.printInfo(); - - } catch (Exception e) { - this.fin = null; - Logging.logError("exception when opening region file '%s': %s", this.file, e); - - } - - return this.fin == null; - } - - public void close() { - if (this.fin != null) { - try { this.fin.close(); } - catch (IOException e) {} - } - } - - public DataInputStream getChunkDataInputStream(int x, int z) { - DataInputStream dis = null; - if (this.fin != null) { - Section section = getChunkSection(x, z); - if ((section != null) && (section.length > 0)) { - int offset = section.startSector * 4096; - try { - // read length of following data (includes version byte) and compressed data version byte - this.fin.seek(offset); - int length = this.fin.readInt(); - byte version = this.fin.readByte(); - // version 1 = gzip compressed, version 2 = zlib/inflater compressed - if ((length > 1) && ((length + 4) < (section.length * 4096)) && (version == 2)) { - // read the compressed data - byte[] compressedChunkData = new byte[length - 1]; - this.fin.read(compressedChunkData); - // create a buffered inflater stream on the compressed data - dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(compressedChunkData)))); - } else { - Logging.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); - } - } catch (Exception e) { - Logging.logError("exception while reading chunk (%d, %d): %s", x, z, e); - dis = null; - } - } - } - return dis; - } - - // basically an in memory byte array that writes its contents - // to a file when it is closed. - private class RegionFileChunkBuffer extends ByteArrayOutputStream { - private final int x; - private final int z; - private final RegionFile regionFile; - - public RegionFileChunkBuffer(RegionFile regionFile, int x, int z) { - super(8096); - this.regionFile = regionFile; - this.x = x; - this.z = z; - } - - public void close() { - this.regionFile.writeCompressedChunk(this.x, this.z, this.buf, this.count); - } - } - - public DataOutputStream getChunkDataOutputStream(int x, int z) { - return new DataOutputStream(new DeflaterOutputStream(new RegionFileChunkBuffer(this, x, z))); - } - - /*private int padToSectorSize() throws IOException { - // pad with 0 so that the file length is a multiple of 4096 bytes - long paddedLength = (this.length + 4095L) & (-4096L); - this.fin.seek(this.length); - for (long i = this.length; i < paddedLength; i++) { - this.fin.writeByte(0); - } - this.length = paddedLength; - return (int) (paddedLength / 4096); - }*/ - - private void writeChunkDataToSection(Section section, byte[] compressedChunkData, int length) throws IOException { - this.fin.seek(((long) section.startSector) * 4096L); - // write version and length - this.fin.writeInt(length + 1); - this.fin.writeByte(2); - // write compressed data - this.fin.write(compressedChunkData, 0, length); - - int endSector = section.startSector + section.length; - if ((endSector + 1) > this.lengthInSectors) { - this.lengthInSectors = endSector + 1; - } - } - - private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, int length) { - // if larger than the existing chunk data or chunk does not exist then need to find the - // first possible file position to write to. This will either be a contiguous strip of - // free sectors longer than the length of the chunk data, or the end of the file (append). - - if (length <= 0) { - Logging.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); - return true; - } - - // free the section this chunk currently occupies - Section currentSection = this.getChunkSection(x, z); - if (currentSection != null) { - this.setFilledSectorArray(currentSection, false); - } - - int requiredSectors = (length + 5 + 4095) / 4096; - Section newSection; - - if ((currentSection != null) && (requiredSectors <= currentSection.length)) { - // if the chunk still fits in it's current location don't move - //RegionManager.logInfo("chunk (%d, %d) fits in current location %d", x, z, currentSection.startSector); - newSection = new Section(currentSection.startSector, requiredSectors); - } else { - // otherwise find a free section large enough to hold the chunk data - newSection = getFreeSection(requiredSectors); - } - - // set the new section to filled - this.setFilledSectorArray(newSection, true); - - boolean error = true; - try { - //RegionManager.logInfo("writing %d bytes to sector %d for chunk (%d, %d)", length, newSection.startSector, x, z); - this.writeChunkDataToSection(newSection, compressedChunkData, length); - // update the header - this.updateChunkSection(x, z, newSection); - error = false; - } catch (IOException e) { - Logging.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); - } - - return error; - } -} +package mapwriter.region; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; + +import mapwriter.util.Logging; + +/* + * Anvil region file reader/writer implementation. This code is very similar to + * RegionFile and RegionFileChunkBuffer from Minecraft. Not sure if it would + * have been better just to use the Minecraft code. + */ + +public class RegionFile +{ + + private final File file; + private int lengthInSectors = 0; + private RandomAccessFile fin = null; + + private Section[] chunkSectionsArray = new Section[4096]; + private int[] timestampArray = new int[4096]; + private List filledSectorArray = null; + + private class Section + { + final int startSector; + final int length; + + Section(int startSector, int length) + { + this.startSector = startSector; + this.length = length; + } + + Section(int sectorAndSize) + { + this((sectorAndSize >> 8) & 0xffffff, sectorAndSize & 0xff); + } + + int getSectorAndSize() + { + return (this.startSector << 8) | (this.length & 0xff); + } + } + + public RegionFile(File file) + { + this.file = file; + } + + @Override + public String toString() + { + return String.format("%s", this.file); + } + + public boolean exists() + { + return this.file.isFile(); + } + + public boolean isOpen() + { + return (this.fin != null); + } + + // set the corresponding bits in filledSectorArray to 'filled' + // for 'count' sectors, starting at 'firstSector'. + private void setFilledSectorArray(Section section, boolean filled) + { + int endSector = section.startSector + section.length; + int sectorsToAppend = (endSector + 1) - this.filledSectorArray.size(); + for (int i = 0; i < sectorsToAppend; i++) + { + this.filledSectorArray.add(Boolean.valueOf(false)); + } + for (int i = section.startSector; i < endSector; i++) + { + if (filled && this.filledSectorArray.get(i)) + { + Logging.logError("sector %d already filled, possible chunk overlap", i); + } + this.filledSectorArray.set(i, Boolean.valueOf(filled)); + } + } + + private boolean checkSectionOverlaps(Section section) + { + // get end sector, limiting to length of the filled sector array as all + // sectors past the + // end of the file are assumed free. + int endSector = Math.min(section.startSector + section.length, this.filledSectorArray.size()); + boolean overlaps = false; + for (int i = section.startSector; i < endSector; i++) + { + if (this.filledSectorArray.get(i)) + { + overlaps = true; + } + } + return overlaps; + } + + private Section getFreeSection(int requiredLength) + { + int start = 0; + int length = 0; + int closestStart = 0; + int closestLength = Integer.MAX_VALUE; + // start at 2 to skip headers + int i; + for (i = 2; i < this.filledSectorArray.size(); i++) + { + if (this.filledSectorArray.get(i)) + { + // sector filled + // if the length of the empty block we found is greater than or + // equal to the required length, and is closer to the required + // length than the previous found length, then set this as the + // new closest length. + // the idea is to use an empty block of exactly the required + // length, rather than one that is larger. + if ((length >= requiredLength) && (length < closestLength)) + { + closestLength = length; + closestStart = start; + // if we find an empty block of exactly the correct length + // then exit the loop. + if (closestLength == requiredLength) + { + break; + } + } + length = 0; + } + else + { + // sector empty + if (length == 0) + { + start = i; + } + length++; + } + } + + if (closestStart <= 0) + { + // append to end of file + closestStart = i; + } + + return new Section(closestStart, requiredLength); + } + + public void printInfo() + { + int freeCount = 0; + int filledCount = 0; + // start at 2 to skip headers + for (int i = 2; i < this.filledSectorArray.size(); i++) + { + if (this.filledSectorArray.get(i)) + { + filledCount++; + } + else + { + freeCount++; + } + } + Logging.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); + + String s = ""; + int i; + for (i = 0; i < this.filledSectorArray.size(); i++) + { + if ((i & 31) == 0) + { + s = String.format("%04x:", i); + } + s += this.filledSectorArray.get(i) ? '1' : '0'; + if ((i & 31) == 31) + { + Logging.logInfo("%s", s); + } + } + if ((i & 31) != 31) + { + Logging.logInfo("%s", s); + } + } + + private Section getChunkSection(int x, int z) + { + return this.chunkSectionsArray[((z & 31) << 5) | (x & 31)]; + } + + private void updateChunkSection(int x, int z, Section newSection) throws IOException + { + int chunkIndex = ((z & 31) << 5) | (x & 31); + this.fin.seek(chunkIndex * 4); + if ((newSection != null) && (newSection.length > 0)) + { + this.fin.writeInt(newSection.getSectorAndSize()); + } + else + { + this.fin.writeInt(0); + } + + this.chunkSectionsArray[chunkIndex] = newSection; + } + + public boolean open() + { + File dir = this.file.getParentFile(); + if (dir.exists()) + { + if (!dir.isDirectory()) + { + Logging.logError("path %s exists and is not a directory", dir); + return true; + } + } + else + { + if (!dir.mkdirs()) + { + Logging.logError("could not create directory %s", dir); + return true; + } + } + try + { + this.fin = new RandomAccessFile(this.file, "rw"); + + // seek to start + this.fin.seek(0); + + this.lengthInSectors = (int) ((this.fin.length() + 4095L) / 4096L); + + this.filledSectorArray = new ArrayList(); + + Arrays.fill(this.chunkSectionsArray, null); + Arrays.fill(this.timestampArray, 0); + + if (this.lengthInSectors < 3) + { + // no chunk data + // fill chunk and timestamp tables with 0's + for (int i = 0; i < 2048; i++) + { + this.fin.writeInt(0); + } + } + else + { + // add a section for each chunk + for (int i = 0; i < 1024; i++) + { + Section section = new Section(this.fin.readInt()); + if (section.length > 0) + { + // make sure chunk does not overlap another + if (!this.checkSectionOverlaps(section)) + { + this.chunkSectionsArray[i] = section; + this.setFilledSectorArray(section, true); + } + else + { + Logging.logError("chunk %d overlaps another chunk, file may be corrupt", i); + } + } + } + for (int i = 0; i < 1024; i++) + { + this.timestampArray[i] = this.fin.readInt(); + } + } + + // this.printInfo(); + + } + catch (Exception e) + { + this.fin = null; + Logging.logError("exception when opening region file '%s': %s", this.file, e); + + } + + return this.fin == null; + } + + public void close() + { + if (this.fin != null) + { + try + { + this.fin.close(); + } + catch (IOException e) + { + } + } + } + + public DataInputStream getChunkDataInputStream(int x, int z) + { + DataInputStream dis = null; + if (this.fin != null) + { + Section section = this.getChunkSection(x, z); + if ((section != null) && (section.length > 0)) + { + int offset = section.startSector * 4096; + try + { + // read length of following data (includes version byte) and + // compressed data version byte + this.fin.seek(offset); + int length = this.fin.readInt(); + byte version = this.fin.readByte(); + // version 1 = gzip compressed, version 2 = zlib/inflater + // compressed + if ((length > 1) && ((length + 4) < (section.length * 4096)) && (version == 2)) + { + // read the compressed data + byte[] compressedChunkData = new byte[length - 1]; + this.fin.read(compressedChunkData); + // create a buffered inflater stream on the compressed + // data + dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(compressedChunkData)))); + } + else + { + Logging.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); + } + } + catch (Exception e) + { + Logging.logError("exception while reading chunk (%d, %d): %s", x, z, e); + dis = null; + } + } + } + return dis; + } + + // basically an in memory byte array that writes its contents + // to a file when it is closed. + private class RegionFileChunkBuffer extends ByteArrayOutputStream + { + private final int x; + private final int z; + private final RegionFile regionFile; + + public RegionFileChunkBuffer(RegionFile regionFile, int x, int z) + { + super(8096); + this.regionFile = regionFile; + this.x = x; + this.z = z; + } + + @Override + public void close() + { + this.regionFile.writeCompressedChunk(this.x, this.z, this.buf, this.count); + } + } + + public DataOutputStream getChunkDataOutputStream(int x, int z) + { + return new DataOutputStream(new DeflaterOutputStream(new RegionFileChunkBuffer(this, x, z))); + } + + /* + * private int padToSectorSize() throws IOException { // pad with 0 so that + * the file length is a multiple of 4096 bytes long paddedLength = + * (this.length + 4095L) & (-4096L); this.fin.seek(this.length); for (long i + * = this.length; i < paddedLength; i++) { this.fin.writeByte(0); } + * this.length = paddedLength; return (int) (paddedLength / 4096); } + */ + + private void writeChunkDataToSection(Section section, byte[] compressedChunkData, int length) throws IOException + { + this.fin.seek((section.startSector) * 4096L); + // write version and length + this.fin.writeInt(length + 1); + this.fin.writeByte(2); + // write compressed data + this.fin.write(compressedChunkData, 0, length); + + int endSector = section.startSector + section.length; + if ((endSector + 1) > this.lengthInSectors) + { + this.lengthInSectors = endSector + 1; + } + } + + private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, int length) + { + // if larger than the existing chunk data or chunk does not exist then + // need to find the + // first possible file position to write to. This will either be a + // contiguous strip of + // free sectors longer than the length of the chunk data, or the end of + // the file (append). + + if (length <= 0) + { + Logging.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); + return true; + } + + // free the section this chunk currently occupies + Section currentSection = this.getChunkSection(x, z); + if (currentSection != null) + { + this.setFilledSectorArray(currentSection, false); + } + + int requiredSectors = (length + 5 + 4095) / 4096; + Section newSection; + + if ((currentSection != null) && (requiredSectors <= currentSection.length)) + { + // if the chunk still fits in it's current location don't move + // RegionManager.logInfo("chunk (%d, %d) fits in current location %d", + // x, z, currentSection.startSector); + newSection = new Section(currentSection.startSector, requiredSectors); + } + else + { + // otherwise find a free section large enough to hold the chunk data + newSection = this.getFreeSection(requiredSectors); + } + + // set the new section to filled + this.setFilledSectorArray(newSection, true); + + boolean error = true; + try + { + // RegionManager.logInfo("writing %d bytes to sector %d for chunk (%d, %d)", + // length, newSection.startSector, x, z); + this.writeChunkDataToSection(newSection, compressedChunkData, length); + // update the header + this.updateChunkSection(x, z, newSection); + error = false; + } + catch (IOException e) + { + Logging.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/region/RegionFileCache.java b/src/main/java/mapwriter/region/RegionFileCache.java index 1b2cdd84..069e3b74 100644 --- a/src/main/java/mapwriter/region/RegionFileCache.java +++ b/src/main/java/mapwriter/region/RegionFileCache.java @@ -4,24 +4,29 @@ import java.util.LinkedHashMap; import java.util.Map; -public class RegionFileCache { - +public class RegionFileCache +{ + // simple Least Recently Used (LRU) cache implementation - class LruCache extends LinkedHashMap { + class LruCache extends LinkedHashMap + { private static final long serialVersionUID = 1L; static final int MAX_REGION_FILES_OPEN = 8; - - public LruCache() { + + public LruCache() + { // initial capacity, loading factor, true for access time ordering super(MAX_REGION_FILES_OPEN * 2, 0.5f, true); } - + // called on every put and putAll call, the entry 'entry' is removed // if this function returns true. @Override - protected boolean removeEldestEntry(Map.Entry entry) { + protected boolean removeEldestEntry(Map.Entry entry) + { boolean ret = false; - if (this.size() > MAX_REGION_FILES_OPEN) { + if (this.size() > MAX_REGION_FILES_OPEN) + { RegionFile regionFile = entry.getValue(); regionFile.close(); ret = true; @@ -29,45 +34,51 @@ protected boolean removeEldestEntry(Map.Entry entry) { return ret; } } - + private LruCache regionFileCache = new LruCache(); private File worldDir; - - public RegionFileCache(File worldDir) { + + public RegionFileCache(File worldDir) + { this.worldDir = worldDir; } - - public void close() { - for (RegionFile regionFile : regionFileCache.values()) { + + public void close() + { + for (RegionFile regionFile : this.regionFileCache.values()) + { regionFile.close(); } this.regionFileCache.clear(); } - - public File getRegionFilePath(int x, int z, int dimension) { + + public File getRegionFilePath(int x, int z, int dimension) + { File dir = this.worldDir; - if (dimension != 0) { + if (dimension != 0) + { dir = new File(dir, "DIM" + dimension); } dir = new File(dir, "region"); - - String filename = String.format("r.%d.%d.mca", - x >> Region.SHIFT, - z >> Region.SHIFT); - + + String filename = String.format("r.%d.%d.mca", x >> Region.SHIFT, z >> Region.SHIFT); + return new File(dir, filename); } - - public boolean regionFileExists(int x, int z, int dimension) { - File regionFilePath = getRegionFilePath(x, z, dimension); + + public boolean regionFileExists(int x, int z, int dimension) + { + File regionFilePath = this.getRegionFilePath(x, z, dimension); return regionFilePath.isFile(); } - - public RegionFile getRegionFile(int x, int z, int dimension) { - File regionFilePath = getRegionFilePath(x, z, dimension); + + public RegionFile getRegionFile(int x, int z, int dimension) + { + File regionFilePath = this.getRegionFilePath(x, z, dimension); String key = regionFilePath.toString(); RegionFile regionFile = this.regionFileCache.get(key); - if (regionFile == null) { + if (regionFile == null) + { regionFile = new RegionFile(regionFilePath); this.regionFileCache.put(key, regionFile); } diff --git a/src/main/java/mapwriter/region/RegionManager.java b/src/main/java/mapwriter/region/RegionManager.java index 425f2924..80044dda 100644 --- a/src/main/java/mapwriter/region/RegionManager.java +++ b/src/main/java/mapwriter/region/RegionManager.java @@ -1,141 +1,161 @@ -package mapwriter.region; - -import java.io.File; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import mapwriter.util.Logging; - -import org.apache.logging.log4j.Logger; - -public class RegionManager { - - // simple Least Recently Used (LRU) cache implementation - class LruCache extends LinkedHashMap { - private final static long serialVersionUID = 1L; - private final static int MAX_LOADED_REGIONS = 64; - - public LruCache() { - // initial capacity, loading factor, true for access time ordering - super(MAX_LOADED_REGIONS * 2, 0.5f, true); - } - - // called on every put and putAll call, the entry 'entry' is removed - // if this function returns true. - @Override - protected boolean removeEldestEntry(Map.Entry entry) { - boolean ret = false; - if (this.size() > MAX_LOADED_REGIONS) { - Region region = entry.getValue(); - region.close(); - ret = true; - } - return ret; - } - } - - private final LruCache regionMap; - - public final File worldDir; - public final File imageDir; - public BlockColours blockColours; - public static Logger logger; - public final RegionFileCache regionFileCache; - - public int maxZoom; - public int minZoom; - - public RegionManager(File worldDir, File imageDir, BlockColours blockColours, int minZoom, int maxZoom) { - this.worldDir = worldDir; - this.imageDir = imageDir; - this.blockColours = blockColours; - this.regionMap = new LruCache(); - this.regionFileCache = new RegionFileCache(worldDir); - this.minZoom = minZoom; - this.maxZoom = maxZoom; - } - - public void close() { - for (Region region : this.regionMap.values()) { - if (region != null) { - region.close(); - } - } - this.regionMap.clear(); - this.regionFileCache.close(); - } - - private static int incrStatsCounter(Map h, String key) { - int n = 1; - if (h.containsKey(key)) { - n = h.get(key) + 1; - } - h.put(key, n); - return n; - } - - public void printLoadedRegionStats() { - Logging.logInfo("loaded region listing:"); - Map stats = new HashMap(); - for (Region region : this.regionMap.values()) { - Logging.logInfo(" %s", region); - incrStatsCounter(stats, String.format("dim%d", region.dimension)); - incrStatsCounter(stats, String.format("zoom%d", region.zoomLevel)); - incrStatsCounter(stats, "total"); - } - Logging.logInfo("loaded region stats:"); - for (Entry e : stats.entrySet()) { - Logging.logInfo(" %s: %d", e.getKey(), e.getValue()); - } - } - - // must not return null - public Region getRegion(int x, int z, int zoomLevel, int dimension) { - Region region = this.regionMap.get(Region.getKey(x, z, zoomLevel, dimension)); - if (region == null) { - // add region - region = new Region(this, x, z, zoomLevel, dimension); - this.regionMap.put(region.key, region); - } - return region; - } - - public void updateChunk(MwChunk chunk) { - Region region = this.getRegion(chunk.x << 4, chunk.z << 4, 0, chunk.dimension); - region.updateChunk(chunk); - } - - public void rebuildRegions(int xStart, int zStart, int w, int h, int dimension) { - // read all zoom level 0 regions - // then find all regions with a backing image at zoom level 0 - - xStart &= Region.MASK; - zStart &= Region.MASK; - w = (w + Region.SIZE) & Region.MASK; - h = (h + Region.SIZE) & Region.MASK; - - Logging.logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); - - for (int rX = xStart; rX < (xStart + w); rX += Region.SIZE) { - for (int rZ = zStart; rZ < (zStart + h); rZ += Region.SIZE) { - Region region = this.getRegion(rX, rZ, 0, dimension); - if (this.regionFileCache.regionFileExists(rX, rZ, dimension)) { - region.clear(); - for (int cz = 0; cz < 32; cz++) { - for (int cx = 0; cx < 32; cx++) { - // load chunk from anvil file - MwChunk chunk = MwChunk.read( - (region.x >> 4) + cx, (region.z >> 4) + cz, - region.dimension, this.regionFileCache - ); - region.updateChunk(chunk); - } - } - } - region.updateZoomLevels(); - } - } - } -} +package mapwriter.region; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import mapwriter.util.Logging; + +import org.apache.logging.log4j.Logger; + +public class RegionManager +{ + + // simple Least Recently Used (LRU) cache implementation + class LruCache extends LinkedHashMap + { + private final static long serialVersionUID = 1L; + private final static int MAX_LOADED_REGIONS = 64; + + public LruCache() + { + // initial capacity, loading factor, true for access time ordering + super(MAX_LOADED_REGIONS * 2, 0.5f, true); + } + + // called on every put and putAll call, the entry 'entry' is removed + // if this function returns true. + @Override + protected boolean removeEldestEntry(Map.Entry entry) + { + boolean ret = false; + if (this.size() > MAX_LOADED_REGIONS) + { + Region region = entry.getValue(); + region.close(); + ret = true; + } + return ret; + } + } + + private final LruCache regionMap; + + public final File worldDir; + public final File imageDir; + public BlockColours blockColours; + public static Logger logger; + public final RegionFileCache regionFileCache; + + public int maxZoom; + public int minZoom; + + public RegionManager(File worldDir, File imageDir, BlockColours blockColours, int minZoom, int maxZoom) + { + this.worldDir = worldDir; + this.imageDir = imageDir; + this.blockColours = blockColours; + this.regionMap = new LruCache(); + this.regionFileCache = new RegionFileCache(worldDir); + this.minZoom = minZoom; + this.maxZoom = maxZoom; + } + + public void close() + { + for (Region region : this.regionMap.values()) + { + if (region != null) + { + region.close(); + } + } + this.regionMap.clear(); + this.regionFileCache.close(); + } + + private static int incrStatsCounter(Map h, String key) + { + int n = 1; + if (h.containsKey(key)) + { + n = h.get(key) + 1; + } + h.put(key, n); + return n; + } + + public void printLoadedRegionStats() + { + Logging.logInfo("loaded region listing:"); + Map stats = new HashMap(); + for (Region region : this.regionMap.values()) + { + Logging.logInfo(" %s", region); + incrStatsCounter(stats, String.format("dim%d", region.dimension)); + incrStatsCounter(stats, String.format("zoom%d", region.zoomLevel)); + incrStatsCounter(stats, "total"); + } + Logging.logInfo("loaded region stats:"); + for (Entry e : stats.entrySet()) + { + Logging.logInfo(" %s: %d", e.getKey(), e.getValue()); + } + } + + // must not return null + public Region getRegion(int x, int z, int zoomLevel, int dimension) + { + Region region = this.regionMap.get(Region.getKey(x, z, zoomLevel, dimension)); + if (region == null) + { + // add region + region = new Region(this, x, z, zoomLevel, dimension); + this.regionMap.put(region.key, region); + } + return region; + } + + public void updateChunk(MwChunk chunk) + { + Region region = this.getRegion(chunk.x << 4, chunk.z << 4, 0, chunk.dimension); + region.updateChunk(chunk); + } + + public void rebuildRegions(int xStart, int zStart, int w, int h, int dimension) + { + // read all zoom level 0 regions + // then find all regions with a backing image at zoom level 0 + + xStart &= Region.MASK; + zStart &= Region.MASK; + w = (w + Region.SIZE) & Region.MASK; + h = (h + Region.SIZE) & Region.MASK; + + Logging.logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); + + for (int rX = xStart; rX < (xStart + w); rX += Region.SIZE) + { + for (int rZ = zStart; rZ < (zStart + h); rZ += Region.SIZE) + { + Region region = this.getRegion(rX, rZ, 0, dimension); + if (this.regionFileCache.regionFileExists(rX, rZ, dimension)) + { + region.clear(); + for (int cz = 0; cz < 32; cz++) + { + for (int cx = 0; cx < 32; cx++) + { + // load chunk from anvil file + MwChunk chunk = MwChunk.read((region.x >> 4) + cx, (region.z >> 4) + cz, region.dimension, this.regionFileCache); + region.updateChunk(chunk); + } + } + } + region.updateZoomLevels(); + } + } + } +} diff --git a/src/main/java/mapwriter/region/SurfacePixels.java b/src/main/java/mapwriter/region/SurfacePixels.java index 38ca62ee..6e55360b 100644 --- a/src/main/java/mapwriter/region/SurfacePixels.java +++ b/src/main/java/mapwriter/region/SurfacePixels.java @@ -1,161 +1,196 @@ -package mapwriter.region; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import javax.imageio.ImageIO; - -import mapwriter.util.Logging; - -public class SurfacePixels { - - protected Region region; - protected File filename; - protected int[] pixels = null; - protected boolean cannotLoad = false; - protected int updateCount = 0; - - public SurfacePixels(Region region, File filename) { - this.region = region; - this.filename = filename; - } - - public void clear() { - if (this.pixels != null) { - Arrays.fill(this.pixels, 0); - } - } - - public void close() { - if (this.updateCount > 0) { - this.save(); - } - this.pixels = null; - } - - private void save() { - if (this.pixels != null) { - saveImage(this.filename, this.pixels, Region.SIZE, Region.SIZE); - this.cannotLoad = false; - } - this.updateCount = 0; - } - - private void load() { - if (!this.cannotLoad) { - this.pixels = loadImage(this.filename, Region.SIZE, Region.SIZE); - if (this.pixels != null) { - // set opaque black pixels to transparent so that - // background texture shows - for (int i = 0; i < this.pixels.length; i++) { - int colour = this.pixels[i]; - if (colour == 0xff000000) { - this.pixels[i] = 0; - } - } - } else { - this.cannotLoad = true; - } - this.updateCount = 0; - } - } - - public int[] getPixels() { - if (this.pixels == null) { - this.load(); - } - return this.pixels; - } - - public int[] getOrAllocatePixels() { - this.getPixels(); - if (this.pixels == null) { - this.pixels = new int[Region.SIZE * Region.SIZE]; - this.clear(); - } - return this.pixels; - } - - public void updateChunk(MwChunk chunk) { - int x = (chunk.x << 4); - int z = (chunk.z << 4); - int offset = this.region.getPixelOffset(x, z); - int[] pixels = this.getOrAllocatePixels(); - // TODO: refactor so that blockColours can be accessed - // more directly - ChunkRender.renderSurface( - this.region.regionManager.blockColours, - chunk, pixels, offset, Region.SIZE, - (chunk.dimension == -1) // use ceiling algorithm for nether - ); - this.region.updateZoomLevels(x, z, MwChunk.SIZE, MwChunk.SIZE); - this.updateCount++; - } - - // get the averaged colour of a 2x2 pixel area in the given pixels - public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { - int p00 = pixels[offset]; - int p01 = pixels[offset + 1]; - int p10 = pixels[offset + scanSize]; - int p11 = pixels[offset + scanSize + 1]; - - // ignore alpha channel - int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); - r >>= 2; - int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); - g >>= 2; - int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); - b >>= 2; - return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); - } - - // update an area of pixels in this region from an area of pixels in srcPixels, - // scaling the pixels by 50%. - public void updateScaled(int[] srcPixels, int srcX, int srcZ, int dstX, int dstZ, int dstW, int dstH) { - int[] dstPixels = this.getOrAllocatePixels(); - for (int j = 0; j < dstH; j++) { - for (int i = 0; i < dstW; i++) { - int srcOffset = ((srcZ + (j * 2)) << Region.SHIFT) + (srcX + (i * 2)); - int dstPixel = getAverageOfPixelQuad(srcPixels, srcOffset, Region.SIZE); - dstPixels[((dstZ + j) << Region.SHIFT) + (dstX + i)] = dstPixel; - } - } - this.updateCount++; - } - - public static void saveImage(File filename, int[] pixels, int w, int h) { - BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - img.setRGB(0, 0, w, h, pixels, 0, w); - - try { - //MwUtil.log("writing region %s to %s", this, this.imageFile); - ImageIO.write(img, "png", filename); - } catch (IOException e) { - Logging.logError("saveImage: error: could not write image to %s", filename); - } - } - - public static int[] loadImage(File filename, int w, int h) { - BufferedImage img = null; - try { - img = ImageIO.read(filename); - } catch (IOException e) { - img = null; - } - int[] pixels = null; - if (img != null) { - if ((img.getWidth() == w) && (img.getHeight() == h)) { - pixels = new int[w * h]; - img.getRGB(0, 0, w, h, pixels, 0, w); - } else { - Logging.logWarning( - "loadImage: image '%s' does not match expected dimensions (got %dx%d expected %dx%d)", - filename, img.getWidth(), img.getHeight(), w, h - ); - } - } - return pixels; - } -} +package mapwriter.region; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +import javax.imageio.ImageIO; + +import mapwriter.util.Logging; + +public class SurfacePixels +{ + + protected Region region; + protected File filename; + protected int[] pixels = null; + protected boolean cannotLoad = false; + protected int updateCount = 0; + + public SurfacePixels(Region region, File filename) + { + this.region = region; + this.filename = filename; + } + + public void clear() + { + if (this.pixels != null) + { + Arrays.fill(this.pixels, 0); + } + } + + public void close() + { + if (this.updateCount > 0) + { + this.save(); + } + this.pixels = null; + } + + private void save() + { + if (this.pixels != null) + { + saveImage(this.filename, this.pixels, Region.SIZE, Region.SIZE); + this.cannotLoad = false; + } + this.updateCount = 0; + } + + private void load() + { + if (!this.cannotLoad) + { + this.pixels = loadImage(this.filename, Region.SIZE, Region.SIZE); + if (this.pixels != null) + { + // set opaque black pixels to transparent so that + // background texture shows + for (int i = 0; i < this.pixels.length; i++) + { + int colour = this.pixels[i]; + if (colour == 0xff000000) + { + this.pixels[i] = 0; + } + } + } + else + { + this.cannotLoad = true; + } + this.updateCount = 0; + } + } + + public int[] getPixels() + { + if (this.pixels == null) + { + this.load(); + } + return this.pixels; + } + + public int[] getOrAllocatePixels() + { + this.getPixels(); + if (this.pixels == null) + { + this.pixels = new int[Region.SIZE * Region.SIZE]; + this.clear(); + } + return this.pixels; + } + + public void updateChunk(MwChunk chunk) + { + int x = (chunk.x << 4); + int z = (chunk.z << 4); + int offset = this.region.getPixelOffset(x, z); + int[] pixels = this.getOrAllocatePixels(); + // TODO: refactor so that blockColours can be accessed + // more directly + ChunkRender.renderSurface(this.region.regionManager.blockColours, chunk, pixels, offset, Region.SIZE, (chunk.dimension == -1) // use + // ceiling + // algorithm + // for + // nether + ); + this.region.updateZoomLevels(x, z, MwChunk.SIZE, MwChunk.SIZE); + this.updateCount++; + } + + // get the averaged colour of a 2x2 pixel area in the given pixels + public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) + { + int p00 = pixels[offset]; + int p01 = pixels[offset + 1]; + int p10 = pixels[offset + scanSize]; + int p11 = pixels[offset + scanSize + 1]; + + // ignore alpha channel + int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); + r >>= 2; + int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); + g >>= 2; + int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); + b >>= 2; + return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); + } + + // update an area of pixels in this region from an area of pixels in + // srcPixels, + // scaling the pixels by 50%. + public void updateScaled(int[] srcPixels, int srcX, int srcZ, int dstX, int dstZ, int dstW, int dstH) + { + int[] dstPixels = this.getOrAllocatePixels(); + for (int j = 0; j < dstH; j++) + { + for (int i = 0; i < dstW; i++) + { + int srcOffset = ((srcZ + (j * 2)) << Region.SHIFT) + (srcX + (i * 2)); + int dstPixel = getAverageOfPixelQuad(srcPixels, srcOffset, Region.SIZE); + dstPixels[((dstZ + j) << Region.SHIFT) + (dstX + i)] = dstPixel; + } + } + this.updateCount++; + } + + public static void saveImage(File filename, int[] pixels, int w, int h) + { + BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + img.setRGB(0, 0, w, h, pixels, 0, w); + + try + { + // MwUtil.log("writing region %s to %s", this, this.imageFile); + ImageIO.write(img, "png", filename); + } + catch (IOException e) + { + Logging.logError("saveImage: error: could not write image to %s", filename); + } + } + + public static int[] loadImage(File filename, int w, int h) + { + BufferedImage img = null; + try + { + img = ImageIO.read(filename); + } + catch (IOException e) + { + img = null; + } + int[] pixels = null; + if (img != null) + { + if ((img.getWidth() == w) && (img.getHeight() == h)) + { + pixels = new int[w * h]; + img.getRGB(0, 0, w, h, pixels, 0, w); + } + else + { + Logging.logWarning("loadImage: image '%s' does not match expected dimensions (got %dx%d expected %dx%d)", filename, img.getWidth(), img.getHeight(), w, h); + } + } + return pixels; + } +} diff --git a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java index 6880844e..58af3714 100644 --- a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java +++ b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java @@ -2,20 +2,24 @@ import mapwriter.region.RegionManager; -public class CloseRegionManagerTask extends Task { +public class CloseRegionManagerTask extends Task +{ private final RegionManager regionManager; - - public CloseRegionManagerTask(RegionManager regionManager) { + + public CloseRegionManagerTask(RegionManager regionManager) + { this.regionManager = regionManager; } - + @Override - public void run() { + public void run() + { this.regionManager.close(); } - + @Override - public void onComplete() { + public void onComplete() + { } } diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java index ca435bd1..4b75b388 100644 --- a/src/main/java/mapwriter/tasks/MergeTask.java +++ b/src/main/java/mapwriter/tasks/MergeTask.java @@ -1,43 +1,50 @@ -package mapwriter.tasks; - -import java.io.File; - -import mapwriter.region.MergeToImage; -import mapwriter.region.RegionManager; -import mapwriter.util.Utils; - -public class MergeTask extends Task { - - final RegionManager regionManager; - final File outputDir; - final String basename; - final int x, z, w, h, dimension; - String msg = ""; - - public MergeTask(RegionManager regionManager, int x, int z, int w, int h, int dimension, File outputDir, String basename) { - this.regionManager = regionManager; - this.x = x; - this.z = z; - this.w = w; - this.h = h; - this.dimension = dimension; - this.outputDir = outputDir; - this.basename = basename; - } - - @Override - public void run() { - int count = MergeToImage.merge(this.regionManager, this.x, this.z, this.w, this.h, this.dimension, this.outputDir, this.basename); - if (count > 0) { - this.msg = String.format("successfully wrote merged images to directory %s", this.outputDir); - } else { - this.msg = String.format("merge error: could not write images to directory %s", this.outputDir); - } - } - - @Override - public void onComplete() { - Utils.printBoth(this.msg); - } - -} +package mapwriter.tasks; + +import java.io.File; + +import mapwriter.region.MergeToImage; +import mapwriter.region.RegionManager; +import mapwriter.util.Utils; + +public class MergeTask extends Task +{ + + final RegionManager regionManager; + final File outputDir; + final String basename; + final int x, z, w, h, dimension; + String msg = ""; + + public MergeTask(RegionManager regionManager, int x, int z, int w, int h, int dimension, File outputDir, String basename) + { + this.regionManager = regionManager; + this.x = x; + this.z = z; + this.w = w; + this.h = h; + this.dimension = dimension; + this.outputDir = outputDir; + this.basename = basename; + } + + @Override + public void run() + { + int count = MergeToImage.merge(this.regionManager, this.x, this.z, this.w, this.h, this.dimension, this.outputDir, this.basename); + if (count > 0) + { + this.msg = String.format("successfully wrote merged images to directory %s", this.outputDir); + } + else + { + this.msg = String.format("merge error: could not write images to directory %s", this.outputDir); + } + } + + @Override + public void onComplete() + { + Utils.printBoth(this.msg); + } + +} diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java index 937d35fd..0e88449c 100644 --- a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java +++ b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java @@ -1,36 +1,40 @@ -package mapwriter.tasks; - -import mapwriter.Mw; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; -import mapwriter.util.Utils; - -public class RebuildRegionsTask extends Task { - - final RegionManager regionManager; - final BlockColours blockColours; - final int x, z, w, h, dimension; - String msg = ""; - - public RebuildRegionsTask(Mw mw, int x, int z, int w, int h, int dimension) { - this.regionManager = mw.regionManager; - this.blockColours = mw.blockColours; - this.x = x; - this.z = z; - this.w = w; - this.h = h; - this.dimension = dimension; - } - - @Override - public void run() { - this.regionManager.blockColours = blockColours; - this.regionManager.rebuildRegions(this.x, this.z, this.w, this.h, this.dimension); - } - - @Override - public void onComplete() { - Utils.printBoth("rebuild task complete"); - } - -} +package mapwriter.tasks; + +import mapwriter.Mw; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; +import mapwriter.util.Utils; + +public class RebuildRegionsTask extends Task +{ + + final RegionManager regionManager; + final BlockColours blockColours; + final int x, z, w, h, dimension; + String msg = ""; + + public RebuildRegionsTask(Mw mw, int x, int z, int w, int h, int dimension) + { + this.regionManager = mw.regionManager; + this.blockColours = mw.blockColours; + this.x = x; + this.z = z; + this.w = w; + this.h = h; + this.dimension = dimension; + } + + @Override + public void run() + { + this.regionManager.blockColours = this.blockColours; + this.regionManager.rebuildRegions(this.x, this.z, this.w, this.h, this.dimension); + } + + @Override + public void onComplete() + { + Utils.printBoth("rebuild task complete"); + } + +} diff --git a/src/main/java/mapwriter/tasks/SaveChunkTask.java b/src/main/java/mapwriter/tasks/SaveChunkTask.java index b90fbc33..091eb264 100644 --- a/src/main/java/mapwriter/tasks/SaveChunkTask.java +++ b/src/main/java/mapwriter/tasks/SaveChunkTask.java @@ -3,21 +3,25 @@ import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; -public class SaveChunkTask extends Task { +public class SaveChunkTask extends Task +{ private final MwChunk chunk; private final RegionManager regionManager; - - public SaveChunkTask(MwChunk chunk, RegionManager regionManager) { + + public SaveChunkTask(MwChunk chunk, RegionManager regionManager) + { this.chunk = chunk; this.regionManager = regionManager; } @Override - public void run() { + public void run() + { this.chunk.write(this.regionManager.regionFileCache); } - + @Override - public void onComplete() { + public void onComplete() + { } } diff --git a/src/main/java/mapwriter/tasks/Task.java b/src/main/java/mapwriter/tasks/Task.java index d2eff63f..30db3b12 100644 --- a/src/main/java/mapwriter/tasks/Task.java +++ b/src/main/java/mapwriter/tasks/Task.java @@ -3,39 +3,51 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -public abstract class Task implements Runnable { - +public abstract class Task implements Runnable +{ + // the task stores its own future private Future future = null; // called by processTaskQueue after the thread completes public abstract void onComplete(); - + // the method that runs in a separate thread // must not access future in run() + @Override public abstract void run(); - + // methods to access the tasks Future variable - public final Future getFuture() { + public final Future getFuture() + { return this.future; } - - public final void setFuture(Future future) { + + public final void setFuture(Future future) + { this.future = future; } - - public final boolean isDone() { + + public final boolean isDone() + { return (this.future != null) ? this.future.isDone() : false; } - - public final void printException() { - if (this.future != null) { - try { + + public final void printException() + { + if (this.future != null) + { + try + { this.future.get(); - } catch (ExecutionException e) { + } + catch (ExecutionException e) + { Throwable rootException = e.getCause(); rootException.printStackTrace(); - } catch (Exception e) { + } + catch (Exception e) + { e.printStackTrace(); } } diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java index 75723738..73a01164 100644 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -6,56 +6,57 @@ import mapwriter.map.MapTexture; import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; -import mapwriter.util.Logging; -public class UpdateSurfaceChunksTask extends Task { +public class UpdateSurfaceChunksTask extends Task +{ MwChunk chunk; RegionManager regionManager; MapTexture mapTexture; public AtomicBoolean Running = new AtomicBoolean(); - - public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) { + + public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) + { this.mapTexture = mw.mapTexture; this.regionManager = mw.regionManager; this.chunk = chunk; } - + @Override - public void run() { - Running.set(true); - //for (MwChunk chunk : this.chunkArray) { - if (chunk != null) { - // update the chunk in the region pixels - this.regionManager.updateChunk(chunk); - // copy updated region pixels to maptexture - this.mapTexture.updateArea( - this.regionManager, - chunk.x << 4, chunk.z << 4, - MwChunk.SIZE, MwChunk.SIZE, chunk.dimension - ); - } - //} - Running.set(false); + public void run() + { + this.Running.set(true); + // for (MwChunk chunk : this.chunkArray) { + if (this.chunk != null) + { + // update the chunk in the region pixels + this.regionManager.updateChunk(this.chunk); + // copy updated region pixels to maptexture + this.mapTexture.updateArea(this.regionManager, this.chunk.x << 4, this.chunk.z << 4, MwChunk.SIZE, MwChunk.SIZE, this.chunk.dimension); + } + // } + this.Running.set(false); } - + @Override - public void onComplete() { + public void onComplete() + { } - + public int getChunkX() { - return chunk.x; + return this.chunk.x; } - + public int getChunkZ() { - return chunk.z; + return this.chunk.z; } public void UpdateChunkData(MwChunk chunk) { this.chunk = chunk; } + public MwChunk getChunk() { return this.chunk; diff --git a/src/main/java/mapwriter/util/Logging.java b/src/main/java/mapwriter/util/Logging.java index c509d305..35aa0475 100644 --- a/src/main/java/mapwriter/util/Logging.java +++ b/src/main/java/mapwriter/util/Logging.java @@ -1,26 +1,31 @@ -package mapwriter.util; - -import mapwriter.forge.MwForge; - -public class Logging -{ - public static void logInfo(String s, Object...args) { - MwForge.logger.info(String.format(s, args)); - } - - public static void logWarning(String s, Object...args) { - MwForge.logger.warn(String.format(s, args)); - } - - public static void logError(String s, Object...args) { - MwForge.logger.error(String.format(s, args)); - } - - public static void debug(String s, Object...args) { - MwForge.logger.debug(String.format(s, args)); - } - - public static void log(String s, Object...args) { - logInfo(String.format(s, args)); - } -} +package mapwriter.util; + +import mapwriter.forge.MwForge; + +public class Logging +{ + public static void logInfo(String s, Object... args) + { + MwForge.logger.info(String.format(s, args)); + } + + public static void logWarning(String s, Object... args) + { + MwForge.logger.warn(String.format(s, args)); + } + + public static void logError(String s, Object... args) + { + MwForge.logger.error(String.format(s, args)); + } + + public static void debug(String s, Object... args) + { + MwForge.logger.debug(String.format(s, args)); + } + + public static void log(String s, Object... args) + { + logInfo(String.format(s, args)); + } +} diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 7f7e9a82..ce871c60 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -1,45 +1,49 @@ -package mapwriter.util; - -import java.util.HashSet; -import java.util.regex.Pattern; - -import com.google.common.collect.Sets; - -import net.minecraft.util.ResourceLocation; - -public final class Reference -{ - public static final String MOD_ID = "MapWriter"; - public static final String MOD_NAME = "MapWriter"; - public static final String VERSION = "@MOD_VERSION@"; - public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; - public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; - public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; - - public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/Versions/master/MwVersion.json"; - - public static final String catOptions = "options"; - public static final String catLargeMapConfig = "largemap"; - public static final String catSmallMapConfig = "smallmap"; - public static final String catFullMapConfig = "fullscreenmap"; - - public static final String PlayerTrailName = "player"; - - public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - - public static final String catWorld = "world"; - public static final String catMarkers = "markers"; - public static final String worldDirConfigName = "mapwriter.cfg"; - public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - public static final ResourceLocation leftArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_left.png"); - public static final ResourceLocation rightArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_right.png"); - - public static final HashSet PROTOCOLS = Sets.newHashSet(new String[] { "http", "https" }); -} +package mapwriter.util; + +import java.util.HashSet; +import java.util.regex.Pattern; + +import net.minecraft.util.ResourceLocation; + +import com.google.common.collect.Sets; + +public final class Reference +{ + public static final String MOD_ID = "MapWriter"; + public static final String MOD_NAME = "MapWriter"; + public static final String VERSION = "@MOD_VERSION@"; + public static final String MOD_GUIFACTORY_CLASS = "mapwriter.gui.ModGuiFactoryHandler"; + public static final String CLIENT_PROXY_CLASS = "mapwriter.forge.ClientProxy"; + public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; + + public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/Versions/master/MwVersion.json"; + + public static final String catOptions = "options"; + public static final String catLargeMapConfig = "largemap"; + public static final String catSmallMapConfig = "smallmap"; + public static final String catFullMapConfig = "fullscreenmap"; + + public static final String PlayerTrailName = "player"; + + public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + + public static final String catWorld = "world"; + public static final String catMarkers = "markers"; + public static final String worldDirConfigName = "mapwriter.cfg"; + public static final String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public static final String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + public static final ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + public static final ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + public static final ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + public static final ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + public static final ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + public static final ResourceLocation leftArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_left.png"); + public static final ResourceLocation rightArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_right.png"); + + public static final HashSet PROTOCOLS = Sets.newHashSet(new String[] + { + "http", + "https" + }); +} diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index d82b6be6..4e241e17 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -1,402 +1,420 @@ -package mapwriter.util; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.WorldRenderer; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -/* -MwRender contains most of the code for drawing the overlay. -This includes: - - loading textures from images - - saving textures to images - - allocating and setting up GL textures - - drawing coloured and textured quads (using minecraft Tesselator class) - -*/ - -public class Render { - public static double zDepth = 0.0D; - public static final double circleSteps = 30.0; - - public static void setColourWithAlphaPercent(int colour, int alphaPercent) { - setColour(((((alphaPercent * 0xff) / 100) & 0xff) << 24) | (colour & 0xffffff)); - } - - public static void setColour(int colour) { - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.color( - (float) ((colour >> 16) & 0xff) / 255.0f, - (float) ((colour >> 8) & 0xff) / 255.0f, - (float) ((colour) & 0xff) / 255.0f, - (float) ((colour >> 24) & 0xff) / 255.0f); - GlStateManager.disableBlend(); - } - - public static void resetColour() { - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - } - - public static int multiplyColours(int c1, int c2) { - float c1A = (float) ((c1 >> 24) & 0xff); - float c1R = (float) ((c1 >> 16) & 0xff); - float c1G = (float) ((c1 >> 8) & 0xff); - float c1B = (float) ((c1 >> 0) & 0xff); - float c2A = (float) ((c2 >> 24) & 0xff); - float c2R = (float) ((c2 >> 16) & 0xff); - float c2G = (float) ((c2 >> 8) & 0xff); - float c2B = (float) ((c2 >> 0) & 0xff); - int r = (int) (c1R * c2R / 255.0f) & 0xff; - int g = (int) (c1G * c2G / 255.0f) & 0xff; - int b = (int) (c1B * c2B / 255.0f) & 0xff; - int a = (int) (c1A * c2A / 255.0f) & 0xff; - return (a << 24) | (r << 16) | (g << 8) | b; - } - - public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { - int p00 = pixels[offset]; - int p01 = pixels[offset + 1]; - int p10 = pixels[offset + scanSize]; - int p11 = pixels[offset + scanSize + 1]; - - // ignore alpha channel - int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); - r >>= 2; - int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); - g >>= 2; - int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); - b >>= 2; - return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); - } - - public static int getAverageColourOfArray(int[] pixels) { - int count = 0; - double totalA = 0.0; - double totalR = 0.0; - double totalG = 0.0; - double totalB = 0.0; - for (int pixel : pixels) { - double a = (double) ((pixel >> 24) & 0xff); - double r = (double) ((pixel >> 16) & 0xff); - double g = (double) ((pixel >> 8) & 0xff); - double b = (double) ((pixel >> 0) & 0xff); - - totalA += a; - totalR += r * a / 255.0; - totalG += g * a / 255.0; - totalB += b * a / 255.0; - - count++; - } - - totalR = totalR * 255.0 / totalA; - totalG = totalG * 255.0 / totalA; - totalB = totalB * 255.0 / totalA; - totalA = totalA / ((double) count); - - return ((((int) (totalA)) & 0xff) << 24) | - ((((int) (totalR)) & 0xff) << 16) | - ((((int) (totalG)) & 0xff) << 8) | - ((((int) (totalB)) & 0xff)); - } - - public static int adjustPixelBrightness(int colour, int brightness) { - int r = ((colour >> 16) & 0xff); - int g = ((colour >> 8) & 0xff); - int b = ((colour >> 0) & 0xff); - r = Math.min(Math.max(0, r + brightness), 0xff); - g = Math.min(Math.max(0, g + brightness), 0xff); - b = Math.min(Math.max(0, b + brightness), 0xff); - return (colour & 0xff000000) | (r << 16) | (g << 8) | (b); - } - - public static int getTextureWidth() { - return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); - } - - public static int getTextureHeight() { - return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); - } - - public static int getBoundTextureId() { - return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); - } - - public static void printBoundTextureInfo(int texture) { - int w = getTextureWidth(); - int h = getTextureHeight(); - int depth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL12.GL_TEXTURE_DEPTH); - int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); - Logging.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); - } - - public static int getMaxTextureSize() { - return GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE); - } - - /* - Drawing Methods - - Note that EntityRenderer.setupOverlayRendering must be called before drawing for the scene - to appear correctly on the overlay. - If these functions are called from the hookUpdateCameraAndRender method of Mw this - will have already been done. - */ - - // draw rectangle with texture stretched to fill the shape - public static void drawTexturedRect(double x, double y, double w, double h) { - drawTexturedRect(x, y, w, h, 0.0D, 0.0D, 1.0D, 1.0D); - } - - // draw rectangle with texture UV coordinates specified (so only part of the texture fills the rectangle). - public static void drawTexturedRect(double x, double y, double w, double h, double u1, double v1, double u2, double v2) { - try { - GlStateManager.enableTexture2D(); - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawingQuads(); - renderer.addVertexWithUV(x + w, y, zDepth, u2, v1); - renderer.addVertexWithUV(x, y, zDepth, u1, v1); - renderer.addVertexWithUV(x, y + h, zDepth, u1, v2); - renderer.addVertexWithUV(x + w, y + h, zDepth, u2, v2); - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.disableBlend(); - } catch (NullPointerException e) { - Logging.log("MwRender.drawTexturedRect: null pointer exception"); - } - } - - public static void drawArrow(double x, double y, double angle, double length) { - // angle the back corners will be drawn at relative to the pointing angle - double arrowBackAngle = 0.75D * Math.PI; - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_FAN); - renderer.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); - renderer.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); - renderer.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); - renderer.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLES); - renderer.addVertex(x1, y1, zDepth); - renderer.addVertex(x2, y2, zDepth); - renderer.addVertex(x3, y3, zDepth); - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawRect(double x, double y, double w, double h) { - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawingQuads(); - renderer.addVertex(x + w, y, zDepth); - renderer.addVertex(x, y, zDepth); - renderer.addVertex(x, y + h, zDepth); - renderer.addVertex(x + w, y + h, zDepth); - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawCircle(double x, double y, double r) { - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_FAN); - renderer.addVertex(x, y, zDepth); - // for some the circle is only drawn if theta is decreasing rather than ascending - double end = Math.PI * 2.0; - double incr = end / circleSteps; - for (double theta = -incr; theta < end; theta += incr) { - renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - } - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawCircleBorder(double x, double y, double r, double width) { - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_STRIP); - // for some the circle is only drawn if theta is decreasing rather than ascending - double end = Math.PI * 2.0; - double incr = end / circleSteps; - double r2 = r + width; - for (double theta = -incr; theta < end; theta += incr) { - renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - renderer.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); - } - //renderer.finishDrawing(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawRectBorder(double x, double y, double w, double h, double bw) { - // top border - Render.drawRect(x - bw, y - bw, w + bw + bw, bw); - // bottom border - Render.drawRect(x - bw, y + h, w + bw + bw, bw); - // left border - Render.drawRect(x - bw, y, bw, h); - // right border - Render.drawRect(x + w, y, bw, h); - } - - public static void drawString(int x, int y, int colour, String formatString, Object...args) { - Minecraft mc = Minecraft.getMinecraft(); - //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRendererObj; - String s = String.format(formatString, args); - fr.drawStringWithShadow(s, x, y, colour); - } - - public static void drawCentredString(int x, int y, int colour, String formatString, Object...args) { - Minecraft mc = Minecraft.getMinecraft(); - //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRendererObj; - String s = String.format(formatString, args); - int w = fr.getStringWidth(s); - fr.drawStringWithShadow(s, x - (w / 2), y, colour); - } - - public static void setCircularStencil(double x, double y, double r) { - GL11.glEnable(GL11.GL_DEPTH_TEST); - // disable drawing to the color buffer. - // circle will only be drawn to depth buffer. - GlStateManager.colorMask(false, false, false, false); - // enable writing to depth buffer - GlStateManager.depthMask(true); - - // Clearing the depth buffer causes problems with shader mods. - // I guess we just have to hope that the rest of the depth buffer - // contains z values greater than 2000 at this stage in the frame - // render. - // It would be much easier to use the stencil buffer instead, but it is - // not specifically requested in the Minecraft LWJGL display setup code. - // So the stencil buffer is only available on GL implementations that - // set it up by default. - - // clear depth buffer to z = 3000.0 - //GlStateManager.clearDepth(3000.0); - //GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT); - - // always write to depth buffer - GlStateManager.depthFunc(GL11.GL_ALWAYS); - - // draw stencil pattern (filled circle at z = 1000.0) - Render.setColour(0xffffffff); - Render.zDepth = 1000.0; - Render.drawCircle(x, y, r); - Render.zDepth = 200.0; - - // re-enable drawing to colour buffer - GlStateManager.colorMask(true, true, true, true); - // disable drawing to depth buffer - GlStateManager.depthMask(false); - // only draw pixels with z values that are greater - // than the value in the depth buffer. - // The overlay is drawn at 2000 so this will pass inside - // the circle (2000 > 1000) but not outside (2000 <= 3000). - GlStateManager.depthFunc(GL11.GL_GREATER); - } - - public static void disableStencil() { - GlStateManager.depthMask(true); - GlStateManager.depthFunc(GL11.GL_LEQUAL); - GlStateManager.disableDepth(); - GL11.glDisable(GL11.GL_DEPTH_TEST); - - //set the zDepth to 0 to make sure there arent any problems drawing other things when circular map isnt drawn - Render.zDepth = 0.0; - } - - // A better implementation of a circular stencil using the stencil buffer - // rather than the depth buffer can be found below. It works only on GL - // implementations that attach a stencil buffer by default (e.g. Intel, but - // not on Nvidia). - // - // To fix this we would need to change the display create line in - // 'Minecraft.java' file from: - // Display.create((new PixelFormat()).withDepthBits(24)); - // to: - // Display.create((new PixelFormat()).withDepthBits(24).withStencilBits(8)); - // - // Then we could use the stencil buffer and the the circular map would have - // far less problems. - // - // I suppose it would also be possible to detect the number of stencil bits - // available at runtime using GL11.glGetInteger(GL11.GL_STENCIL_BITS) and - // only use the depth buffer stencil algorithm if it returns 0. But this - // doesn't solve the problem of the stencil buffer not being initialized by - // default on some systems. - - /*public static void setCircularStencil(double x, double y, double r) { - GL11.glEnable(GL11.GL_STENCIL_TEST); - // disable drawing to the color and depth buffers. - // circle will only be drawn to stencil buffer. - GL11.glColorMask(false, false, false, false); - GL11.glDepthMask(false); - // set up stencil func and op so that a 1 is always written to the stencil buffer - // whenever a pixel is drawn. - GL11.glStencilFunc(GL11.GL_NEVER, 1, 0x01); - // replace stencil buffer value with 1 whenever stencil test fails. - // keep stencil buffer value otherwise. - GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_KEEP, GL11.GL_KEEP); - // enable writing to 8 bits of the stencil buffer - GL11.glStencilMask(0x01); - // clear stencil buffer, with mask 0xff - GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); - // draw stencil pattern - Render.setColour(0xffffffff); - Render.drawCircle(x, y, r); - - // re-enable drawing to colour and depth buffers - GL11.glColorMask(true, true, true, true); - // probably shouldn't enable? -> GL11.glDepthMask(true); - // disable writing to stencil buffer - GL11.glStencilMask(0x00); - // draw only when stencil buffer value == 1 (inside circle) - GL11.glStencilFunc(GL11.GL_EQUAL, 1, 0x01); - } - - public static void disableStencil() { - GL11.glDisable(GL11.GL_STENCIL_TEST); - }*/ +package mapwriter.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/* + * MwRender contains most of the code for drawing the overlay. This includes: - + * loading textures from images - saving textures to images - allocating and + * setting up GL textures - drawing coloured and textured quads (using minecraft + * Tesselator class) + */ + +public class Render +{ + public static double zDepth = 0.0D; + public static final double circleSteps = 30.0; + + public static void setColourWithAlphaPercent(int colour, int alphaPercent) + { + setColour(((((alphaPercent * 0xff) / 100) & 0xff) << 24) | (colour & 0xffffff)); + } + + public static void setColour(int colour) + { + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.color(((colour >> 16) & 0xff) / 255.0f, ((colour >> 8) & 0xff) / 255.0f, ((colour) & 0xff) / 255.0f, ((colour >> 24) & 0xff) / 255.0f); + GlStateManager.disableBlend(); + } + + public static void resetColour() + { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } + + public static int multiplyColours(int c1, int c2) + { + float c1A = (c1 >> 24) & 0xff; + float c1R = (c1 >> 16) & 0xff; + float c1G = (c1 >> 8) & 0xff; + float c1B = (c1 >> 0) & 0xff; + float c2A = (c2 >> 24) & 0xff; + float c2R = (c2 >> 16) & 0xff; + float c2G = (c2 >> 8) & 0xff; + float c2B = (c2 >> 0) & 0xff; + int r = (int) ((c1R * c2R) / 255.0f) & 0xff; + int g = (int) ((c1G * c2G) / 255.0f) & 0xff; + int b = (int) ((c1B * c2B) / 255.0f) & 0xff; + int a = (int) ((c1A * c2A) / 255.0f) & 0xff; + return (a << 24) | (r << 16) | (g << 8) | b; + } + + public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) + { + int p00 = pixels[offset]; + int p01 = pixels[offset + 1]; + int p10 = pixels[offset + scanSize]; + int p11 = pixels[offset + scanSize + 1]; + + // ignore alpha channel + int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); + r >>= 2; + int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); + g >>= 2; + int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); + b >>= 2; + return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); + } + + public static int getAverageColourOfArray(int[] pixels) + { + int count = 0; + double totalA = 0.0; + double totalR = 0.0; + double totalG = 0.0; + double totalB = 0.0; + for (int pixel : pixels) + { + double a = (pixel >> 24) & 0xff; + double r = (pixel >> 16) & 0xff; + double g = (pixel >> 8) & 0xff; + double b = (pixel >> 0) & 0xff; + + totalA += a; + totalR += (r * a) / 255.0; + totalG += (g * a) / 255.0; + totalB += (b * a) / 255.0; + + count++; + } + + totalR = (totalR * 255.0) / totalA; + totalG = (totalG * 255.0) / totalA; + totalB = (totalB * 255.0) / totalA; + totalA = totalA / (count); + + return ((((int) (totalA)) & 0xff) << 24) | ((((int) (totalR)) & 0xff) << 16) | ((((int) (totalG)) & 0xff) << 8) | ((((int) (totalB)) & 0xff)); + } + + public static int adjustPixelBrightness(int colour, int brightness) + { + int r = ((colour >> 16) & 0xff); + int g = ((colour >> 8) & 0xff); + int b = ((colour >> 0) & 0xff); + r = Math.min(Math.max(0, r + brightness), 0xff); + g = Math.min(Math.max(0, g + brightness), 0xff); + b = Math.min(Math.max(0, b + brightness), 0xff); + return (colour & 0xff000000) | (r << 16) | (g << 8) | (b); + } + + public static int getTextureWidth() + { + return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + } + + public static int getTextureHeight() + { + return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + } + + public static int getBoundTextureId() + { + return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + } + + public static void printBoundTextureInfo(int texture) + { + int w = getTextureWidth(); + int h = getTextureHeight(); + int depth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL12.GL_TEXTURE_DEPTH); + int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + Logging.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); + } + + public static int getMaxTextureSize() + { + return GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE); + } + + /* + * Drawing Methods + * + * Note that EntityRenderer.setupOverlayRendering must be called before + * drawing for the scene to appear correctly on the overlay. If these + * functions are called from the hookUpdateCameraAndRender method of Mw this + * will have already been done. + */ + + // draw rectangle with texture stretched to fill the shape + public static void drawTexturedRect(double x, double y, double w, double h) + { + drawTexturedRect(x, y, w, h, 0.0D, 0.0D, 1.0D, 1.0D); + } + + // draw rectangle with texture UV coordinates specified (so only part of the + // texture fills the rectangle). + public static void drawTexturedRect(double x, double y, double w, double h, double u1, double v1, double u2, double v2) + { + try + { + GlStateManager.enableTexture2D(); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawingQuads(); + renderer.addVertexWithUV(x + w, y, zDepth, u2, v1); + renderer.addVertexWithUV(x, y, zDepth, u1, v1); + renderer.addVertexWithUV(x, y + h, zDepth, u1, v2); + renderer.addVertexWithUV(x + w, y + h, zDepth, u2, v2); + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.disableBlend(); + } + catch (NullPointerException e) + { + Logging.log("MwRender.drawTexturedRect: null pointer exception"); + } + } + + public static void drawArrow(double x, double y, double angle, double length) + { + // angle the back corners will be drawn at relative to the pointing + // angle + double arrowBackAngle = 0.75D * Math.PI; + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_FAN); + renderer.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); + renderer.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); + renderer.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); + renderer.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + public static void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) + { + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLES); + renderer.addVertex(x1, y1, zDepth); + renderer.addVertex(x2, y2, zDepth); + renderer.addVertex(x3, y3, zDepth); + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + public static void drawRect(double x, double y, double w, double h) + { + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawingQuads(); + renderer.addVertex(x + w, y, zDepth); + renderer.addVertex(x, y, zDepth); + renderer.addVertex(x, y + h, zDepth); + renderer.addVertex(x + w, y + h, zDepth); + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + public static void drawCircle(double x, double y, double r) + { + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_FAN); + renderer.addVertex(x, y, zDepth); + // for some the circle is only drawn if theta is decreasing rather than + // ascending + double end = Math.PI * 2.0; + double incr = end / circleSteps; + for (double theta = -incr; theta < end; theta += incr) + { + renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + } + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + public static void drawCircleBorder(double x, double y, double r, double width) + { + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer renderer = tessellator.getWorldRenderer(); + renderer.startDrawing(GL11.GL_TRIANGLE_STRIP); + // for some the circle is only drawn if theta is decreasing rather than + // ascending + double end = Math.PI * 2.0; + double incr = end / circleSteps; + double r2 = r + width; + for (double theta = -incr; theta < end; theta += incr) + { + renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + renderer.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); + } + // renderer.finishDrawing(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + public static void drawRectBorder(double x, double y, double w, double h, double bw) + { + // top border + Render.drawRect(x - bw, y - bw, w + bw + bw, bw); + // bottom border + Render.drawRect(x - bw, y + h, w + bw + bw, bw); + // left border + Render.drawRect(x - bw, y, bw, h); + // right border + Render.drawRect(x + w, y, bw, h); + } + + public static void drawString(int x, int y, int colour, String formatString, Object... args) + { + Minecraft mc = Minecraft.getMinecraft(); + // mc.renderEngine.resetBoundTexture(); + FontRenderer fr = mc.fontRendererObj; + String s = String.format(formatString, args); + fr.drawStringWithShadow(s, x, y, colour); + } + + public static void drawCentredString(int x, int y, int colour, String formatString, Object... args) + { + Minecraft mc = Minecraft.getMinecraft(); + // mc.renderEngine.resetBoundTexture(); + FontRenderer fr = mc.fontRendererObj; + String s = String.format(formatString, args); + int w = fr.getStringWidth(s); + fr.drawStringWithShadow(s, x - (w / 2), y, colour); + } + + public static void setCircularStencil(double x, double y, double r) + { + GL11.glEnable(GL11.GL_DEPTH_TEST); + // disable drawing to the color buffer. + // circle will only be drawn to depth buffer. + GlStateManager.colorMask(false, false, false, false); + // enable writing to depth buffer + GlStateManager.depthMask(true); + + // Clearing the depth buffer causes problems with shader mods. + // I guess we just have to hope that the rest of the depth buffer + // contains z values greater than 2000 at this stage in the frame + // render. + // It would be much easier to use the stencil buffer instead, but it is + // not specifically requested in the Minecraft LWJGL display setup code. + // So the stencil buffer is only available on GL implementations that + // set it up by default. + + // clear depth buffer to z = 3000.0 + // GlStateManager.clearDepth(3000.0); + // GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT); + + // always write to depth buffer + GlStateManager.depthFunc(GL11.GL_ALWAYS); + + // draw stencil pattern (filled circle at z = 1000.0) + Render.setColour(0xffffffff); + Render.zDepth = 1000.0; + Render.drawCircle(x, y, r); + Render.zDepth = 200.0; + + // re-enable drawing to colour buffer + GlStateManager.colorMask(true, true, true, true); + // disable drawing to depth buffer + GlStateManager.depthMask(false); + // only draw pixels with z values that are greater + // than the value in the depth buffer. + // The overlay is drawn at 2000 so this will pass inside + // the circle (2000 > 1000) but not outside (2000 <= 3000). + GlStateManager.depthFunc(GL11.GL_GREATER); + } + + public static void disableStencil() + { + GlStateManager.depthMask(true); + GlStateManager.depthFunc(GL11.GL_LEQUAL); + GlStateManager.disableDepth(); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + // set the zDepth to 0 to make sure there arent any problems drawing + // other things when circular map isnt drawn + Render.zDepth = 0.0; + } + + // A better implementation of a circular stencil using the stencil buffer + // rather than the depth buffer can be found below. It works only on GL + // implementations that attach a stencil buffer by default (e.g. Intel, but + // not on Nvidia). + // + // To fix this we would need to change the display create line in + // 'Minecraft.java' file from: + // Display.create((new PixelFormat()).withDepthBits(24)); + // to: + // Display.create((new PixelFormat()).withDepthBits(24).withStencilBits(8)); + // + // Then we could use the stencil buffer and the the circular map would have + // far less problems. + // + // I suppose it would also be possible to detect the number of stencil bits + // available at runtime using GL11.glGetInteger(GL11.GL_STENCIL_BITS) and + // only use the depth buffer stencil algorithm if it returns 0. But this + // doesn't solve the problem of the stencil buffer not being initialized by + // default on some systems. + + /* + * public static void setCircularStencil(double x, double y, double r) { + * GL11.glEnable(GL11.GL_STENCIL_TEST); // disable drawing to the color and + * depth buffers. // circle will only be drawn to stencil buffer. + * GL11.glColorMask(false, false, false, false); GL11.glDepthMask(false); // + * set up stencil func and op so that a 1 is always written to the stencil + * buffer // whenever a pixel is drawn. GL11.glStencilFunc(GL11.GL_NEVER, 1, + * 0x01); // replace stencil buffer value with 1 whenever stencil test + * fails. // keep stencil buffer value otherwise. + * GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_KEEP, GL11.GL_KEEP); // enable + * writing to 8 bits of the stencil buffer GL11.glStencilMask(0x01); // + * clear stencil buffer, with mask 0xff + * GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); // draw stencil pattern + * Render.setColour(0xffffffff); Render.drawCircle(x, y, r); + * + * // re-enable drawing to colour and depth buffers GL11.glColorMask(true, + * true, true, true); // probably shouldn't enable? -> + * GL11.glDepthMask(true); // disable writing to stencil buffer + * GL11.glStencilMask(0x00); // draw only when stencil buffer value == 1 + * (inside circle) GL11.glStencilFunc(GL11.GL_EQUAL, 1, 0x01); } + * + * public static void disableStencil() { + * GL11.glDisable(GL11.GL_STENCIL_TEST); } + */ } \ No newline at end of file diff --git a/src/main/java/mapwriter/util/Texture.java b/src/main/java/mapwriter/util/Texture.java index e4928857..080a44a9 100644 --- a/src/main/java/mapwriter/util/Texture.java +++ b/src/main/java/mapwriter/util/Texture.java @@ -1,168 +1,206 @@ -package mapwriter.util; - -import java.nio.IntBuffer; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -public class Texture { - - private int id; - public final int w; - public final int h; - private final IntBuffer pixelBuf; - - // allocate new texture and fill from IntBuffer - public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int textureWrap) { - this.id = GlStateManager.generateTexture(); - this.w = w; - this.h = h; - this.pixelBuf = Utils.allocateDirectIntBuffer(w * h); - this.fillRect(0, 0, w, h, fillColour); - this.pixelBuf.position(0); - this.bind(); - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, w, h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - this.setTexParameters(minFilter, maxFilter, textureWrap); - } - - public Texture(int w, int h, int fillColour) { - this(w, h, fillColour, GL11.GL_LINEAR, GL11.GL_NEAREST, GL12.GL_CLAMP_TO_EDGE); - } - - // create from existing texture - public Texture(int id) { - this.id = id; - this.bind(); - this.w = Render.getTextureWidth(); - this.h = Render.getTextureHeight(); - this.pixelBuf = Utils.allocateDirectIntBuffer(this.w * this.h); - this.getPixelsFromExistingTexture(); - Logging.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); - } - - // free up the resources used by the GL texture - public synchronized void close() { - if (this.id != 0) { - try { - GlStateManager.deleteTexture(this.id); - } catch (NullPointerException e) { - Logging.log("MwTexture.close: null pointer exception (texture %d)", this.id); - } - this.id = 0; - } - } - - public void setPixelBufPosition(int i) { - this.pixelBuf.position(i); - } - - public void pixelBufPut(int pixel) { - this.pixelBuf.put(pixel); - } - - public synchronized void fillRect(int x, int y, int w, int h, int colour) { - int offset = (y * this.w) + x; - for (int j = 0; j < h; j++) { - this.pixelBuf.position(offset + (j * this.w)); - for (int i = 0; i < w; i++) { - this.pixelBuf.put(colour); - } - } - } - - // Copy a rectangular sub-region of dimensions 'w' x 'h' from the pixel buffer to the array 'pixels'. - public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize, TextureAtlasSprite icon) { - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - try - { - this.pixelBuf.position(bufOffset + (i * this.w)); - this.pixelBuf.get(pixels, offset + (i * scanSize), w); - } - catch (IllegalArgumentException e) - { - Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (icon name: %s; height: %d; width: %d; MaxU: %f; MinU: %f; MaxV: %f; MinV: %f)", icon.getIconName(), icon.getIconHeight(), icon.getIconWidth(), icon.getMaxU(),icon.getMinU(), icon.getMaxV(),icon.getMinV()); - Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (pos: %d)", bufOffset + (i * this.w)); - Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (buffersize: %d)", this.pixelBuf.limit()); - } - - } - } - - // Copy a rectangular sub-region of dimensions 'w' x 'h' from the array 'pixels' to the pixel buffer. - public synchronized void setRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - this.pixelBuf.position(bufOffset + (i * this.w)); - this.pixelBuf.put(pixels, offset + (i * scanSize), w); - } - } - - public synchronized void setRGB(int x, int y, int colour) { - this.pixelBuf.put((y * this.w) + x, colour); - } - - public synchronized int getRGB(int x, int y) { - return this.pixelBuf.get((y * this.w) + x); - } - - public void bind() { - GlStateManager.bindTexture(this.id); - } - - // set texture scaling and wrapping parameters - public void setTexParameters(int minFilter, int maxFilter, int textureWrap) { - this.bind(); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, textureWrap); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, textureWrap); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, minFilter); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, maxFilter); - } - - public void setLinearScaling(boolean enabled) { - this.bind(); - if (enabled) { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - } else { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - } - } - - // update texture from pixels in pixelBuf - public synchronized void updateTextureArea(int x, int y, int w, int h) { - try { - this.bind(); - GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, this.w); - this.pixelBuf.position((y * this.w) + x); - GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); - } catch (NullPointerException e) { - Logging.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); - } - } - - public synchronized void updateTexture() { - this.bind(); - this.pixelBuf.position(0); - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.w, this.h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - } - - // copy pixels from GL texture to pixelBuf - private synchronized void getPixelsFromExistingTexture() { - try { - this.bind(); - this.pixelBuf.clear(); - GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - // getTexImage does not seem to advance the buffer position, so flip does not work here - // this.pixelBuf.flip() - this.pixelBuf.limit(this.w * this.h); - } catch (NullPointerException e) { - Logging.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); - } - } -} +package mapwriter.util; + +import java.nio.IntBuffer; + +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +public class Texture +{ + + private int id; + public final int w; + public final int h; + private final IntBuffer pixelBuf; + + // allocate new texture and fill from IntBuffer + public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int textureWrap) + { + this.id = GlStateManager.generateTexture(); + this.w = w; + this.h = h; + this.pixelBuf = Utils.allocateDirectIntBuffer(w * h); + this.fillRect(0, 0, w, h, fillColour); + this.pixelBuf.position(0); + this.bind(); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, w, h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + this.setTexParameters(minFilter, maxFilter, textureWrap); + } + + public Texture(int w, int h, int fillColour) + { + this(w, h, fillColour, GL11.GL_LINEAR, GL11.GL_NEAREST, GL12.GL_CLAMP_TO_EDGE); + } + + // create from existing texture + public Texture(int id) + { + this.id = id; + this.bind(); + this.w = Render.getTextureWidth(); + this.h = Render.getTextureHeight(); + this.pixelBuf = Utils.allocateDirectIntBuffer(this.w * this.h); + this.getPixelsFromExistingTexture(); + Logging.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); + } + + // free up the resources used by the GL texture + public synchronized void close() + { + if (this.id != 0) + { + try + { + GlStateManager.deleteTexture(this.id); + } + catch (NullPointerException e) + { + Logging.log("MwTexture.close: null pointer exception (texture %d)", this.id); + } + this.id = 0; + } + } + + public void setPixelBufPosition(int i) + { + this.pixelBuf.position(i); + } + + public void pixelBufPut(int pixel) + { + this.pixelBuf.put(pixel); + } + + public synchronized void fillRect(int x, int y, int w, int h, int colour) + { + int offset = (y * this.w) + x; + for (int j = 0; j < h; j++) + { + this.pixelBuf.position(offset + (j * this.w)); + for (int i = 0; i < w; i++) + { + this.pixelBuf.put(colour); + } + } + } + + // Copy a rectangular sub-region of dimensions 'w' x 'h' from the pixel + // buffer to the array 'pixels'. + public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize, TextureAtlasSprite icon) + { + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) + { + try + { + this.pixelBuf.position(bufOffset + (i * this.w)); + this.pixelBuf.get(pixels, offset + (i * scanSize), w); + } + catch (IllegalArgumentException e) + { + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (icon name: %s; height: %d; width: %d; MaxU: %f; MinU: %f; MaxV: %f; MinV: %f)", icon.getIconName(), icon.getIconHeight(), icon.getIconWidth(), icon.getMaxU(), icon.getMinU(), icon.getMaxV(), icon.getMinV()); + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (pos: %d)", bufOffset + (i * this.w)); + Logging.logWarning("MwTexture.getRGB: IllegalArgumentException (buffersize: %d)", this.pixelBuf.limit()); + } + + } + } + + // Copy a rectangular sub-region of dimensions 'w' x 'h' from the array + // 'pixels' to the pixel buffer. + public synchronized void setRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) + { + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) + { + this.pixelBuf.position(bufOffset + (i * this.w)); + this.pixelBuf.put(pixels, offset + (i * scanSize), w); + } + } + + public synchronized void setRGB(int x, int y, int colour) + { + this.pixelBuf.put((y * this.w) + x, colour); + } + + public synchronized int getRGB(int x, int y) + { + return this.pixelBuf.get((y * this.w) + x); + } + + public void bind() + { + GlStateManager.bindTexture(this.id); + } + + // set texture scaling and wrapping parameters + public void setTexParameters(int minFilter, int maxFilter, int textureWrap) + { + this.bind(); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, textureWrap); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, textureWrap); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, minFilter); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, maxFilter); + } + + public void setLinearScaling(boolean enabled) + { + this.bind(); + if (enabled) + { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + } + else + { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + } + } + + // update texture from pixels in pixelBuf + public synchronized void updateTextureArea(int x, int y, int w, int h) + { + try + { + this.bind(); + GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, this.w); + this.pixelBuf.position((y * this.w) + x); + GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); + } + catch (NullPointerException e) + { + Logging.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); + } + } + + public synchronized void updateTexture() + { + this.bind(); + this.pixelBuf.position(0); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.w, this.h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + } + + // copy pixels from GL texture to pixelBuf + private synchronized void getPixelsFromExistingTexture() + { + try + { + this.bind(); + this.pixelBuf.clear(); + GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + // getTexImage does not seem to advance the buffer position, so flip + // does not work here + // this.pixelBuf.flip() + this.pixelBuf.limit(this.w * this.h); + } + catch (NullPointerException e) + { + Logging.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); + } + } +} diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 36eabeb0..d330743e 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -1,303 +1,365 @@ -package mapwriter.util; - -import java.io.File; -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mapwriter.config.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.resources.I18n; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class Utils -{ - public static int[] integerListToIntArray(List list) - { - // convert List of integers to integer array - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = list.get(i); - } - return array; - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return Reference.patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - //send an ingame chat message and console log - public static void printBoth(String msg) { - EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - Logging.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } - - public static String getWorldName() { - String worldName; - - if (Minecraft.getMinecraft().isIntegratedServerRunning()) - { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - else - { - worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; - if (!Config.portNumberInWorldNameEnabled) - { - worldName = worldName.substring(0, worldName.indexOf(":")); - } - else - { - if(worldName.indexOf(":")==-1){//standard port is missing. Adding it - worldName += "_25565"; - } else { - worldName = worldName.replace(":", "_"); - } - } - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - public static void openWebLink(URI p_175282_1_) - { - try - { - Class oclass = Class.forName("java.awt.Desktop"); - Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); - oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {p_175282_1_}); - } - catch (Throwable throwable) - { - Logging.logError("Couldn\'t open link %s", throwable.getStackTrace().toString()); - } - } - - public static String stringArrayToString(String[] arr) - { - StringBuilder builder = new StringBuilder(); - for(String s : arr) { - builder.append(I18n.format(s, new Object[0])); - builder.append("\n"); - } - return builder.toString(); - } - public static int getMaxWidth(String[] arr, String[] arr2) - { - FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj; - int Width = 1; - for(int i=0; i w2 ? w1 : w2; - Width = Width > wTot ? Width : wTot; - } - return Width; - } - - private static int[] colours = new int[] { - 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, - 0xff8000, 0x8000ff}; - // static so that current index is shared between all markers - public static int colourIndex = 0; - private static int getColoursLengt() - { - return colours.length; - } - public static int getCurrentColour() { - return 0xff000000 | colours[colourIndex]; - } - public static int getNextColour() - { - Utils.colourIndex = (Utils.colourIndex + 1) % Utils.getColoursLengt(); - return Utils.getCurrentColour(); - } - public static int getPrevColour() { - Utils.colourIndex = (Utils.colourIndex + Utils.getColoursLengt() - 1) % Utils.getColoursLengt(); - return Utils.getCurrentColour(); - } - - - /* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * @since 4.37 - * @author Jaroslav Tulach - */ - /* - * Create a typesafe copy of a raw map. - * @param rawMap an unchecked map - * @param keyType the desired supertype of the keys - * @param valueType the desired supertype of the values - * @param strict true to throw a ClassCastException if the raw map has an invalid key or value, - * false to skip over such map entries (warnings may be logged) - * @return a typed map guaranteed to contain only keys and values assignable - * to the named types (or they may be null) - * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if strict was true - */ - @SuppressWarnings("rawtypes") - public static - Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException { - Map m2 = new HashMap(rawMap.size() * 4 / 3 + 1); - Iterator it = rawMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); - try { - m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); - } catch (ClassCastException x) { - if (strict) { - throw x; - } else { - System.out.println("not assignable"); - } - } - } - return m2; - } -} +package mapwriter.util; + +import java.io.File; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mapwriter.config.Config; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.resources.I18n; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class Utils +{ + public static int[] integerListToIntArray(List list) + { + // convert List of integers to integer array + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) + { + array[i] = list.get(i); + } + return array; + } + + public static String mungeString(String s) + { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return Reference.patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) + { + int i = 0; + File outputFile; + if (dir != null) + { + outputFile = new File(dir, baseName + "." + ext); + } + else + { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) + { + if (dir != null) + { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } + else + { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + // send an ingame chat message and console log + public static void printBoth(String msg) + { + EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) + { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + Logging.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) + { + File dimDir; + if (dimension != 0) + { + dimDir = new File(worldDir, "DIM" + dimension); + } + else + { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) + { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean + // Anderson) + // works by making sure all bits to the right of the highest set bit are 1, + // then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) + { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() + { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) + { + int dx = ((chunk.xPosition << 4) + 8) - x; + int dz = ((chunk.zPosition << 4) + 8) - z; + return (dx * dx) + (dz * dz); + } + + public static String getWorldName() + { + String worldName; + + if (Minecraft.getMinecraft().isIntegratedServerRunning()) + { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + else + { + worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; + if (!Config.portNumberInWorldNameEnabled) + { + worldName = worldName.substring(0, worldName.indexOf(":")); + } + else + { + if (worldName.indexOf(":") == -1) + {// standard port is missing. Adding it + worldName += "_25565"; + } + else + { + worldName = worldName.replace(":", "_"); + } + } + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") + { + worldName = "default"; + } + return worldName; + } + + public static void openWebLink(URI p_175282_1_) + { + try + { + Class oclass = Class.forName("java.awt.Desktop"); + Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]); + oclass.getMethod("browse", new Class[] + { + URI.class + }).invoke(object, new Object[] + { + p_175282_1_ + }); + } + catch (Throwable throwable) + { + Logging.logError("Couldn\'t open link %s", throwable.getStackTrace().toString()); + } + } + + public static String stringArrayToString(String[] arr) + { + StringBuilder builder = new StringBuilder(); + for (String s : arr) + { + builder.append(I18n.format(s, new Object[0])); + builder.append("\n"); + } + return builder.toString(); + } + + public static int getMaxWidth(String[] arr, String[] arr2) + { + FontRenderer fontRendererObj = Minecraft.getMinecraft().fontRendererObj; + int Width = 1; + for (int i = 0; i < arr.length; i++) + { + int w1 = 0; + int w2 = 0; + + if (i < arr.length) + { + String s = I18n.format(arr[i], new Object[0]); + w1 = fontRendererObj.getStringWidth(s); + } + if ((arr2 != null) && (i < arr2.length)) + { + String s = I18n.format(arr2[i], new Object[0]); + w2 = fontRendererObj.getStringWidth(s); + w2 += 65; + } + int wTot = w1 > w2 ? w1 : w2; + Width = Width > wTot ? Width : wTot; + } + return Width; + } + + private static int[] colours = new int[] + { + 0xff0000, + 0x00ff00, + 0x0000ff, + 0xffff00, + 0xff00ff, + 0x00ffff, + 0xff8000, + 0x8000ff + }; + // static so that current index is shared between all markers + public static int colourIndex = 0; + + private static int getColoursLengt() + { + return colours.length; + } + + public static int getCurrentColour() + { + return 0xff000000 | colours[colourIndex]; + } + + public static int getNextColour() + { + Utils.colourIndex = (Utils.colourIndex + 1) % Utils.getColoursLengt(); + return Utils.getCurrentColour(); + } + + public static int getPrevColour() + { + Utils.colourIndex = ((Utils.colourIndex + Utils.getColoursLengt()) - 1) % Utils.getColoursLengt(); + return Utils.getCurrentColour(); + } + + /* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You may + * not use this file except in compliance with the License. You can obtain a + * copy of the License at http://www.netbeans.org/cddl-gplv2.html or + * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific language + * governing permissions and limitations under the License. When + * distributing the software, include this License Header Notice in each + * file and include the License file at nbbuild/licenses/CDDL-GPL-2-CP. Sun + * designates this particular file as subject to the "Classpath" exception + * as provided by Sun in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the License + * Header, with the fields enclosed by brackets [] replaced by your own + * identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or + * GPL Version 2] license." If you do not indicate a single choice of + * license, a recipient has the option to distribute your version of this + * file under either the CDDL, the GPL Version 2 or to extend the choice of + * license to its licensees as provided above. However, if you add GPL + * Version 2 code and therefore, elected the GPL Version 2 license, then the + * option applies only if the new code is made subject to such option by the + * copyright holder. + * + * @since 4.37 + * + * @author Jaroslav Tulach + */ + /* + * Create a typesafe copy of a raw map. + * + * @param rawMap an unchecked map + * + * @param keyType the desired supertype of the keys + * + * @param valueType the desired supertype of the values + * + * @param strict true to throw a ClassCastException if the raw + * map has an invalid key or value, false to skip over such map entries + * (warnings may be logged) + * + * @return a typed map guaranteed to contain only keys and values assignable + * to the named types (or they may be null) + * + * @throws ClassCastException if some key or value in the raw map was not + * well-typed, and only if strict was true + */ + @SuppressWarnings("rawtypes") + public static Map checkedMapByCopy(Map rawMap, Class keyType, Class valueType, boolean strict) throws ClassCastException + { + Map m2 = new HashMap(((rawMap.size() * 4) / 3) + 1); + Iterator it = rawMap.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry e = (Map.Entry) it.next(); + try + { + m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue())); + } + catch (ClassCastException x) + { + if (strict) + { + throw x; + } + else + { + System.out.println("not assignable"); + } + } + } + return m2; + } +} diff --git a/src/main/java/mapwriter/util/VersionCheck.java b/src/main/java/mapwriter/util/VersionCheck.java index 46707db3..936a85a4 100644 --- a/src/main/java/mapwriter/util/VersionCheck.java +++ b/src/main/java/mapwriter/util/VersionCheck.java @@ -1,75 +1,88 @@ -package mapwriter.util; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import net.minecraftforge.fml.common.Loader; - -import org.apache.commons.io.IOUtils; - -public class VersionCheck implements Runnable { - private static boolean isLatestVersion = true; - private static String latestVersion = ""; - private static String updateURL = ""; - - /** - * @author jabelar - * @link - * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making - * -mod.html - */ - - @Override - public void run() { - InputStream in = null; - try { - in = new URL(Reference.VersionURL).openStream(); - } catch (MalformedURLException e) { - } catch (IOException e) { - } - - try { - List list = IOUtils.readLines(in); - int index = -1; - for (int i = 0; i < list.size(); i++) { - if (list.get(i) - .contains(Loader.instance().getMCVersionString())) { - index = i; - break; - } - } - - String version = list.get(index + 1); - version = version.replace("\"modVersion\":\"", ""); - version = version.replace("\",", ""); - version = version.replace(" ", ""); - latestVersion = version; - - String updateURL = list.get(index + 3); - updateURL = updateURL.replace("\"updateURL\":\"", ""); - updateURL = updateURL.replace("\",", ""); - updateURL = updateURL.replace(" ", ""); - VersionCheck.updateURL = updateURL; - - isLatestVersion = Reference.VERSION.equals(version); - } catch (IOException e) { - } - - } - - public static boolean isLatestVersion() { - return isLatestVersion; - } - - public static String getLatestVersion() { - return latestVersion; - } - - public static String getUpdateURL() - { - return updateURL; - } -} +package mapwriter.util; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import net.minecraftforge.fml.common.Loader; + +import org.apache.commons.io.IOUtils; + +public class VersionCheck implements Runnable +{ + private static boolean isLatestVersion = true; + private static String latestVersion = ""; + private static String updateURL = ""; + + /** + * @author jabelar + * @link + * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making + * -mod.html + */ + + @Override + public void run() + { + InputStream in = null; + try + { + in = new URL(Reference.VersionURL).openStream(); + } + catch (MalformedURLException e) + { + } + catch (IOException e) + { + } + + try + { + List list = IOUtils.readLines(in); + int index = -1; + for (int i = 0; i < list.size(); i++) + { + if (list.get(i).contains(Loader.instance().getMCVersionString())) + { + index = i; + break; + } + } + + String version = list.get(index + 1); + version = version.replace("\"modVersion\":\"", ""); + version = version.replace("\",", ""); + version = version.replace(" ", ""); + latestVersion = version; + + String updateURL = list.get(index + 3); + updateURL = updateURL.replace("\"updateURL\":\"", ""); + updateURL = updateURL.replace("\",", ""); + updateURL = updateURL.replace(" ", ""); + VersionCheck.updateURL = updateURL; + + isLatestVersion = Reference.VERSION.equals(version); + } + catch (IOException e) + { + } + + } + + public static boolean isLatestVersion() + { + return isLatestVersion; + } + + public static String getLatestVersion() + { + return latestVersion; + } + + public static String getUpdateURL() + { + return updateURL; + } +} From ddd387a9ea5326db39a85ed57c44e8d0a8b28af4 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 01:25:15 +0200 Subject: [PATCH 083/109] comment fix --- .../java/mapwriter/BackgroundExecutor.java | 60 ++++++++++--------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index ffde2da6..a9653d04 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -13,34 +13,40 @@ import mapwriter.util.Logging; import net.minecraft.world.ChunkCoordIntPair; +// @formatter:off /* - * This class handles executing and managing 'tasks'. A single background thread - * runs tasks in the sequence they are added (via addTask()). A linked list FIFO - * queue of every unfinished task is processed every time the processTaskQueue - * method is called. processTaskQueue checks the task at the front of the queue - * to see if the background thread has processed it. If it the task is complete - * processTaskQueue calls the onComplete() method of the task and removes it - * from the queue. If it is not complete the task is added to the front of the - * queue again. In this way the tasks are always processed sequentially, in the - * order they were added to the queue. - * - * Tasks are extensions of the base Task class. There are two abstract methods - * which must be overwritten by the extending class. void run() Is executed in - * the background thread when the executor reaches this task. void onComplete() - * Is called by processTaskQueue() when the task is done (after the run method - * is complete). This method runs in the main thread so is a good place to copy - * the results of the run() method. - * - * The run() method of a task added to the queue is guaranteed to be run before - * the run() method of the next task added. Likewise the onComplete() method of - * the first task is guaranteed to be run before the onComplete() of the second - * task. However the run() method of any class added after a Task may be - * executed before the onComplete() method of the earlier Task is called. - * - * e.g. addTask(Task1) addTask(Task2) addTask(Task3) - * - * may run in the order: Task1.run() Task2.run() Task1.onComplete() Task3.run() - * Task2.onComplete() Task3.onComplete() + * This class handles executing and managing 'tasks'. + * A single background thread runs tasks in the sequence they are added (via addTask()). + * A linked list FIFO queue of every unfinished task is processed every time the processTaskQueue method is called. + * processTaskQueue checks the task at the front of the queue to see if the background thread has processed it. + * If it the task is complete processTaskQueue calls the onComplete() method of the task and removes it from the queue. + * If it is not complete the task is added to the front of the queue again. + * In this way the tasks are always processed sequentially, in the order they were added to the queue. + * + * Tasks are extensions of the base Task class. + * There are two abstract methods which must be overwritten by the extending class. + * void run() + * Is executed in the background thread when the executor reaches this task. + * void onComplete() + * Is called by processTaskQueue() when the task is done (after the run method is complete). + * This method runs in the main thread so is a good place to copy the results of the run() method. + * + * The run() method of a task added to the queue is guaranteed to be run before the run() method of the next task + * added. Likewise the onComplete() method of the first task is guaranteed to be run before the onComplete() of the second + * task. However the run() method of any class added after a Task may be executed before the onComplete() method of + * the earlier Task is called. + * + * e.g. addTask(Task1) + * addTask(Task2) + * addTask(Task3) + * + * may run in the order: + * Task1.run() + * Task2.run() + * Task1.onComplete() + * Task3.run() + * Task2.onComplete() + * Task3.onComplete() */ public class BackgroundExecutor From 4a6478f35dbda7336f7e9d988bf6b4022f4ab191 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 02:57:04 +0200 Subject: [PATCH 084/109] Refactoring --- src/main/java/mapwriter/map/MapTexture.java | 1 + .../mapwriter/{map => tasks}/MapUpdateViewTask.java | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) rename src/main/java/mapwriter/{map => tasks}/MapUpdateViewTask.java (82%) diff --git a/src/main/java/mapwriter/map/MapTexture.java b/src/main/java/mapwriter/map/MapTexture.java index f0f406b4..1353252a 100644 --- a/src/main/java/mapwriter/map/MapTexture.java +++ b/src/main/java/mapwriter/map/MapTexture.java @@ -6,6 +6,7 @@ import mapwriter.BackgroundExecutor; import mapwriter.region.Region; import mapwriter.region.RegionManager; +import mapwriter.tasks.MapUpdateViewTask; import mapwriter.util.Texture; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/mapwriter/map/MapUpdateViewTask.java b/src/main/java/mapwriter/tasks/MapUpdateViewTask.java similarity index 82% rename from src/main/java/mapwriter/map/MapUpdateViewTask.java rename to src/main/java/mapwriter/tasks/MapUpdateViewTask.java index 4fb7b77e..3b72197a 100644 --- a/src/main/java/mapwriter/map/MapUpdateViewTask.java +++ b/src/main/java/mapwriter/tasks/MapUpdateViewTask.java @@ -1,7 +1,8 @@ -package mapwriter.map; +package mapwriter.tasks; +import mapwriter.map.MapTexture; +import mapwriter.map.MapViewRequest; import mapwriter.region.RegionManager; -import mapwriter.tasks.Task; public class MapUpdateViewTask extends Task { @@ -33,4 +34,10 @@ public void onComplete() // set currentView in mapTexture to requestedView this.mapTexture.setLoaded(this.req); } + + @Override + public boolean CheckForDuplicate() + { + return false; + } } From ad69322564a9eb88b85c44d0ac068d14a54af731 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 02:57:34 +0200 Subject: [PATCH 085/109] Make it posible to scroll when in the colour display --- .../gui/ScrollableColorSelector.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/gui/ScrollableColorSelector.java b/src/main/java/mapwriter/gui/ScrollableColorSelector.java index 5d9591f2..99fc85f8 100644 --- a/src/main/java/mapwriter/gui/ScrollableColorSelector.java +++ b/src/main/java/mapwriter/gui/ScrollableColorSelector.java @@ -128,7 +128,31 @@ public void mouseClicked(int x, int y, int button) public void mouseDWheelScrolled(int x, int y, int direction) { - // TODO Auto-generated method stub + this.ScrollableNumericTextBoxColourRed.mouseDWheelScrolled(x, y, direction); + this.ScrollableNumericTextBoxColourGreen.mouseDWheelScrolled(x, y, direction); + this.ScrollableNumericTextBoxColourBlue.mouseDWheelScrolled(x, y, direction); + + if (this.posWithinColourField(x, y)) + { + this.colourFieldScroll(-direction); + } + } + + public boolean posWithinColourField(int x, int y) + { + return (x >= this.colourFieldX) && (y >= this.colourFieldY) && (x <= (this.colourFieldW + this.colourFieldX)) && (y <= (this.colourFieldH + this.colourFieldY)); + } + + public void colourFieldScroll(int direction) + { + if (direction > 0) + { + this.nextElement(); + } + else if (direction < 0) + { + this.previousElement(); + } } public void KeyTyped(char c, int key) From bf76c00da9303cd564fe49408f728446d4a9a1bc Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 11:02:17 +0100 Subject: [PATCH 086/109] have the save task, and the update task only have one task in que, and if a new one gets added just update the chunck data to the latest --- .../java/mapwriter/BackgroundExecutor.java | 75 +++++++++++-------- src/main/java/mapwriter/region/MwChunk.java | 6 ++ .../tasks/CloseRegionManagerTask.java | 6 ++ src/main/java/mapwriter/tasks/MergeTask.java | 6 ++ .../mapwriter/tasks/RebuildRegionsTask.java | 6 ++ .../java/mapwriter/tasks/SaveChunkTask.java | 47 +++++++++++- src/main/java/mapwriter/tasks/Task.java | 3 + .../tasks/UpdateSurfaceChunksTask.java | 54 ++++++++----- 8 files changed, 149 insertions(+), 54 deletions(-) diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index a9653d04..77cb7529 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -54,8 +54,8 @@ public class BackgroundExecutor private ExecutorService executor; private LinkedList taskQueue; - private Map chunksUpdating = new HashMap(); public boolean closed = false; + private boolean doDiag = true; public BackgroundExecutor() { @@ -68,34 +68,25 @@ public boolean addTask(Task task) { if (!this.closed) { - if (task instanceof UpdateSurfaceChunksTask) - { - UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; - Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); - - if (!this.chunksUpdating.containsKey(coords)) - { - Future future = this.executor.submit(task); - task.setFuture(future); - this.taskQueue.add(task); - this.chunksUpdating.put(coords, task); - } - else - { - UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask) this.chunksUpdating.get(coords); - if (task2.Running.get() == false) - { - task2.UpdateChunkData(((UpdateSurfaceChunksTask) task).getChunk()); - } - } - } - else + if (!task.CheckForDuplicate()) { Future future = this.executor.submit(task); task.setFuture(future); this.taskQueue.add(task); } - + + //bit for diagnostics on task left to optimize code + if (this.tasksRemaining() > 500 && doDiag) + { + doDiag = false; + Logging.logError("Taskque went over 500 starting diagnostic"); + taskLeftPerType(); + Logging.logError("End of diagnostic"); + } + else + { + doDiag = true; + } } else { @@ -118,15 +109,7 @@ public boolean processTaskQueue() { task.printException(); task.onComplete(); - - if (task instanceof UpdateSurfaceChunksTask) - { - UpdateSurfaceChunksTask updatetask = (UpdateSurfaceChunksTask) task; - Long coords = ChunkCoordIntPair.chunkXZ2Int(updatetask.getChunkX(), updatetask.getChunkZ()); - - this.chunksUpdating.remove(coords, updatetask); - - } + processed = true; } else @@ -167,6 +150,7 @@ public boolean close() boolean error = true; try { + taskLeftPerType(); // stop accepting new tasks this.executor.shutdown(); // process remaining tasks @@ -183,4 +167,29 @@ public boolean close() this.closed = true; return error; } + + private void taskLeftPerType() + { + HashMap tasksLeft = new HashMap(); + + for (Task t : this.taskQueue) + { + String className = t.getClass().toString(); + if (tasksLeft.containsKey(className)) + { + tasksLeft.put(className, ((Integer)tasksLeft.get(className)) + 1); + } + else + { + tasksLeft.put(className, 1); + } + } + + for (Map.Entry entry : tasksLeft.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + Logging.log("waiting for %d %s to finish...", value, key); + } + } } diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 1c29dbf0..04c52900 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -18,6 +18,7 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; +import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.chunk.NibbleArray; import net.minecraftforge.fml.common.FMLLog; @@ -514,4 +515,9 @@ public synchronized boolean write(RegionFileCache regionFileCache) return error; } + + public Long getCoordIntPair() + { + return ChunkCoordIntPair.chunkXZ2Int(this.x, this.z); + } } diff --git a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java index 58af3714..a8a12246 100644 --- a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java +++ b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java @@ -22,4 +22,10 @@ public void run() public void onComplete() { } + + @Override + public boolean CheckForDuplicate() + { + return false; + } } diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java index 4b75b388..4c1dc81c 100644 --- a/src/main/java/mapwriter/tasks/MergeTask.java +++ b/src/main/java/mapwriter/tasks/MergeTask.java @@ -47,4 +47,10 @@ public void onComplete() Utils.printBoth(this.msg); } + @Override + public boolean CheckForDuplicate() + { + return false; + } + } diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java index 0e88449c..1d1cf110 100644 --- a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java +++ b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java @@ -37,4 +37,10 @@ public void onComplete() Utils.printBoth("rebuild task complete"); } + @Override + public boolean CheckForDuplicate() + { + return false; + } + } diff --git a/src/main/java/mapwriter/tasks/SaveChunkTask.java b/src/main/java/mapwriter/tasks/SaveChunkTask.java index 091eb264..5064e6d3 100644 --- a/src/main/java/mapwriter/tasks/SaveChunkTask.java +++ b/src/main/java/mapwriter/tasks/SaveChunkTask.java @@ -1,12 +1,19 @@ package mapwriter.tasks; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import net.minecraft.world.ChunkCoordIntPair; import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; public class SaveChunkTask extends Task { - private final MwChunk chunk; - private final RegionManager regionManager; + private MwChunk chunk; + private RegionManager regionManager; + private AtomicBoolean Running = new AtomicBoolean(); + private static Map chunksUpdating = new HashMap(); public SaveChunkTask(MwChunk chunk, RegionManager regionManager) { @@ -17,11 +24,47 @@ public SaveChunkTask(MwChunk chunk, RegionManager regionManager) @Override public void run() { + this.Running.set(true); this.chunk.write(this.regionManager.regionFileCache); } @Override public void onComplete() { + Long coords = this.chunk.getCoordIntPair(); + this.chunksUpdating.remove(coords,this); + this.Running.set(false); + } + + @Override + public boolean CheckForDuplicate() + { + Long coords = this.chunk.getCoordIntPair(); + + if (!this.chunksUpdating.containsKey(coords)) + { + this.chunksUpdating.put(coords, this); + return false; + } + else + { + SaveChunkTask task2 = (SaveChunkTask) this.chunksUpdating.get(coords); + if (task2.Running.get() == false) + { + task2.UpdateChunkData(this.chunk,this.regionManager); + } + else + { + this.chunksUpdating.put(coords, this); + return false; + } + } + return true; + } + + public void UpdateChunkData(MwChunk chunk, RegionManager regionManager) + { + this.chunk = chunk; + this.regionManager = regionManager; } } diff --git a/src/main/java/mapwriter/tasks/Task.java b/src/main/java/mapwriter/tasks/Task.java index 30db3b12..9aef1054 100644 --- a/src/main/java/mapwriter/tasks/Task.java +++ b/src/main/java/mapwriter/tasks/Task.java @@ -17,6 +17,9 @@ public abstract class Task implements Runnable @Override public abstract void run(); + //returns false if the task has to be added to a new future + public abstract boolean CheckForDuplicate(); + // methods to access the tasks Future variable public final Future getFuture() { diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java index 73a01164..d0615ba9 100644 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -1,7 +1,11 @@ package mapwriter.tasks; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.world.ChunkCoordIntPair; import mapwriter.Mw; import mapwriter.map.MapTexture; import mapwriter.region.MwChunk; @@ -9,10 +13,11 @@ public class UpdateSurfaceChunksTask extends Task { - MwChunk chunk; - RegionManager regionManager; - MapTexture mapTexture; - public AtomicBoolean Running = new AtomicBoolean(); + private MwChunk chunk; + private RegionManager regionManager; + private MapTexture mapTexture; + private AtomicBoolean Running = new AtomicBoolean(); + private static Map chunksUpdating = new HashMap(); public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) { @@ -25,7 +30,6 @@ public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) public void run() { this.Running.set(true); - // for (MwChunk chunk : this.chunkArray) { if (this.chunk != null) { // update the chunk in the region pixels @@ -33,23 +37,14 @@ public void run() // copy updated region pixels to maptexture this.mapTexture.updateArea(this.regionManager, this.chunk.x << 4, this.chunk.z << 4, MwChunk.SIZE, MwChunk.SIZE, this.chunk.dimension); } - // } - this.Running.set(false); } @Override public void onComplete() { - } - - public int getChunkX() - { - return this.chunk.x; - } - - public int getChunkZ() - { - return this.chunk.z; + Long coords = this.chunk.getCoordIntPair(); + this.chunksUpdating.remove(coords, this); + this.Running.set(false); } public void UpdateChunkData(MwChunk chunk) @@ -57,8 +52,29 @@ public void UpdateChunkData(MwChunk chunk) this.chunk = chunk; } - public MwChunk getChunk() + @Override + public boolean CheckForDuplicate() { - return this.chunk; + Long coords = ChunkCoordIntPair.chunkXZ2Int(this.chunk.x, this.chunk.z); + + if (!this.chunksUpdating.containsKey(coords)) + { + this.chunksUpdating.put(coords, this); + return false; + } + else + { + UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask) this.chunksUpdating.get(coords); + if (task2.Running.get() == false) + { + task2.UpdateChunkData(this.chunk); + } + else + { + this.chunksUpdating.put(coords, this); + return false; + } + } + return true; } } From 0d215715ec0b52ef78bf42202b8a27dcebf0aa40 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 11:06:43 +0100 Subject: [PATCH 087/109] updted version to a new release --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index 465ce931..3d1197df 100644 --- a/build.properties +++ b/build.properties @@ -3,6 +3,6 @@ mod_group=vectron mc_version=1.8 forge_version=11.14.3.1450 mcp_version=snapshot_20150615 -mod_version=2.2.9-Beta-2 +mod_version=2.2.10 curse_project_id=231387 release_type=beta \ No newline at end of file From b5904d286550b9e2df2035493ac5997f9f2e186d Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 11:16:31 +0100 Subject: [PATCH 088/109] formatting, small compile fix --- .../java/mapwriter/BackgroundExecutor.java | 36 +++++------ src/main/java/mapwriter/CircularHashMap.java | 6 +- src/main/java/mapwriter/config/Config.java | 10 +-- .../java/mapwriter/config/MapModeConfig.java | 22 +++---- .../java/mapwriter/forge/MwKeyHandler.java | 4 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 10 +-- src/main/java/mapwriter/gui/MwGui.java | 64 +++++++++---------- .../mapwriter/gui/MwGuiMarkerListOverlay.java | 2 +- .../mapwriter/map/UndergroundTexture.java | 12 ++-- .../java/mapwriter/overlay/OverlaySlime.java | 2 +- src/main/java/mapwriter/region/MwChunk.java | 2 +- .../java/mapwriter/tasks/SaveChunkTask.java | 17 +++-- src/main/java/mapwriter/tasks/Task.java | 6 +- .../tasks/UpdateSurfaceChunksTask.java | 13 ++-- src/main/java/mapwriter/util/Reference.java | 4 +- src/main/java/mapwriter/util/Render.java | 6 +- src/main/java/mapwriter/util/Utils.java | 58 ++++++++--------- .../java/mapwriter/util/VersionCheck.java | 3 +- 18 files changed, 137 insertions(+), 140 deletions(-) diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java index 77cb7529..5c3411c8 100644 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -9,9 +9,7 @@ import java.util.concurrent.TimeUnit; import mapwriter.tasks.Task; -import mapwriter.tasks.UpdateSurfaceChunksTask; import mapwriter.util.Logging; -import net.minecraft.world.ChunkCoordIntPair; // @formatter:off /* @@ -22,7 +20,7 @@ * If it the task is complete processTaskQueue calls the onComplete() method of the task and removes it from the queue. * If it is not complete the task is added to the front of the queue again. * In this way the tasks are always processed sequentially, in the order they were added to the queue. - * + * * Tasks are extensions of the base Task class. * There are two abstract methods which must be overwritten by the extending class. * void run() @@ -30,16 +28,16 @@ * void onComplete() * Is called by processTaskQueue() when the task is done (after the run method is complete). * This method runs in the main thread so is a good place to copy the results of the run() method. - * + * * The run() method of a task added to the queue is guaranteed to be run before the run() method of the next task * added. Likewise the onComplete() method of the first task is guaranteed to be run before the onComplete() of the second * task. However the run() method of any class added after a Task may be executed before the onComplete() method of * the earlier Task is called. - * + * * e.g. addTask(Task1) * addTask(Task2) * addTask(Task3) - * + * * may run in the order: * Task1.run() * Task2.run() @@ -74,18 +72,18 @@ public boolean addTask(Task task) task.setFuture(future); this.taskQueue.add(task); } - + //bit for diagnostics on task left to optimize code - if (this.tasksRemaining() > 500 && doDiag) + if ((this.tasksRemaining() > 500) && this.doDiag) { - doDiag = false; + this.doDiag = false; Logging.logError("Taskque went over 500 starting diagnostic"); - taskLeftPerType(); + this.taskLeftPerType(); Logging.logError("End of diagnostic"); } else { - doDiag = true; + this.doDiag = true; } } else @@ -109,7 +107,7 @@ public boolean processTaskQueue() { task.printException(); task.onComplete(); - + processed = true; } else @@ -150,7 +148,7 @@ public boolean close() boolean error = true; try { - taskLeftPerType(); + this.taskLeftPerType(); // stop accepting new tasks this.executor.shutdown(); // process remaining tasks @@ -171,7 +169,7 @@ public boolean close() private void taskLeftPerType() { HashMap tasksLeft = new HashMap(); - + for (Task t : this.taskQueue) { String className = t.getClass().toString(); @@ -184,12 +182,12 @@ private void taskLeftPerType() tasksLeft.put(className, 1); } } - + for (Map.Entry entry : tasksLeft.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - - Logging.log("waiting for %d %s to finish...", value, key); + String key = entry.getKey(); + Object value = entry.getValue(); + + Logging.log("waiting for %d %s to finish...", value, key); } } } diff --git a/src/main/java/mapwriter/CircularHashMap.java b/src/main/java/mapwriter/CircularHashMap.java index 2064011d..bc8339f0 100644 --- a/src/main/java/mapwriter/CircularHashMap.java +++ b/src/main/java/mapwriter/CircularHashMap.java @@ -11,15 +11,15 @@ public class CircularHashMap /* * A hash map where each node is linked to the previous and next nodes in * the order of insertion. - * + * * The 'head' node is the most recently added node. Its next pointer links * to the first node added, forming a circle. - * + * * The getNextEntry and getPrevEntry methods use an internal pointer to the * 'current' node, and return either the current nodes 'next' or 'prev' node * respectively. The current node becomes the node that was returned, such * that repeated calls traverse all nodes in the map. - * + * * Most methods are similar to those in the java.util.Map interface. The * CircularHashMap class does not implement Map however as some of the * required methods seemed unnecessary. diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 615e37b3..17e242da 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -5,11 +5,11 @@ public class Config { public static final String[] backgroundModeStringArray = - { - "none", - "static", - "panning" - }; + { + "none", + "static", + "panning" + }; // configuration options public static boolean linearTextureScalingDef = true; diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index e04a0643..90895764 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -8,19 +8,19 @@ public class MapModeConfig { public final String configCategory; public static final String[] coordsModeStringArray = - { - "disabled", - "small", - "large" - }; + { + "disabled", + "small", + "large" + }; public static final String[] miniMapPositionStringArray = - { - "top right", - "top left", - "bottom right", - "bottom left" - }; + { + "top right", + "top left", + "bottom right", + "bottom left" + }; public boolean enabledDef = true; public boolean enabled = this.enabledDef; diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java index 8b3deaf9..88021410 100644 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -27,7 +27,7 @@ public class MwKeyHandler public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); public final KeyBinding[] keys = - { + { keyMapGui, keyNewMarker, keyMapMode, @@ -36,7 +36,7 @@ public class MwKeyHandler keyZoomIn, keyZoomOut, keyUndergroundMode - }; + }; public MwKeyHandler() { diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index 37378bee..1e77595b 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -23,8 +23,8 @@ public class ModGuiConfig extends GuiConfig public ModGuiConfig(GuiScreen guiScreen) { super(guiScreen, getConfigElements(), - // new - // ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), + // new + // ConfigElement(ConfigurationHandler.configuration.getCategory(Reference.catOptions)).getChildElements(), Reference.MOD_ID, "Options", false, @@ -137,9 +137,9 @@ public Boolean getCurrentValue() public Boolean[] getCurrentValues() { return new Boolean[] - { - this.getCurrentValue() - }; + { + this.getCurrentValue() + }; } @Override diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index 6073a0db..fec4d32c 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -42,7 +42,7 @@ public class MwGui extends GuiScreen private MapRenderer map; private String[] HelpText1 = new String[] - { + { "Keys:", "", " Space", @@ -67,9 +67,9 @@ public class MwGui extends GuiScreen "mw.gui.mwgui.helptext.7", "mw.gui.mwgui.helptext.8", "mw.gui.mwgui.helptext.9" - }; + }; private String[] HelpText2 = new String[] - { + { "", "", "mw.gui.mwgui.helptext.nextmarkergroup", @@ -83,7 +83,7 @@ public class MwGui extends GuiScreen "mw.gui.mwgui.helptext.regenerate", "mw.gui.mwgui.helptext.undergroundmap", "mw.gui.mwgui.helptext.markerlist" - }; + }; private final static double PAN_FACTOR = 0.3D; @@ -168,27 +168,27 @@ public void initGui() public void initLabels() { this.helpLabel = new MwGuiLabel(new String[] - { - "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]" - }, null, menuX, menuY, true, false, this.width, this.height); + { + "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]" + }, null, menuX, menuY, true, false, this.width, this.height); this.optionsLabel = new MwGuiLabel(new String[] - { - "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]" - }, null, 0, 0, true, false, this.width, this.height); + { + "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]" + }, null, 0, 0, true, false, this.width, this.height); this.dimensionLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); this.groupLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); this.overlayLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", VersionCheck.getLatestVersion()); this.updateLabel = new MwGuiLabel(new String[] - { - updateString - }, null, 0, 0, true, false, this.width, this.height); + { + updateString + }, null, 0, 0, true, false, this.width, this.height); this.helpTooltipLabel = new MwGuiLabel(this.HelpText1, this.HelpText2, 0, 0, true, false, this.width, this.height); this.updateTooltipLabel = new MwGuiLabel(new String[] - { - VersionCheck.getUpdateURL() - }, null, 0, 0, true, false, this.width, this.height); + { + VersionCheck.getUpdateURL() + }, null, 0, 0, true, false, this.width, this.height); this.statusLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); this.markerLabel = new MwGuiLabel(null, null, 0, 0, true, true, this.width, this.height); @@ -651,9 +651,9 @@ public void drawStatus(int bX, int bY, int bZ) this.statusLabel.setCoords(x, this.height - 21); this.statusLabel.setText(new String[] - { - builder.toString() - }, null); + { + builder.toString() + }, null); this.statusLabel.draw(); } @@ -723,10 +723,10 @@ private void drawMarkerLabel(int mouseX, int mouseY, float f) if (marker != null) { this.markerLabel.setText(new String[] - { + { marker.name, String.format("(%d, %d, %d)", marker.x, marker.y, marker.z) - }, null); + }, null); this.markerLabel.setCoords(mouseX + 8, mouseY); this.markerLabel.draw(); } @@ -735,10 +735,10 @@ private void drawMarkerLabel(int mouseX, int mouseY, float f) if (this.isPlayerNearScreenPos(mouseX, mouseY)) { this.markerLabel.setText(new String[] - { + { this.mc.thePlayer.getDisplayNameString(), String.format("(%d, %d, %d)", this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt) - }, null); + }, null); this.markerLabel.setCoords(mouseX + 8, mouseY); this.markerLabel.draw(); } @@ -750,23 +750,23 @@ private void drawLabel(int mouseX, int mouseY, float f) this.optionsLabel.draw(); String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); this.dimensionLabel.setText(new String[] - { - dimString - }, null); + { + dimString + }, null); this.dimensionLabel.draw(); String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); this.groupLabel.setText(new String[] - { - groupString - }, null); + { + groupString + }, null); this.groupLabel.draw(); String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); this.overlayLabel.setText(new String[] - { - overlayString - }, null); + { + overlayString + }, null); this.overlayLabel.draw(); if (!VersionCheck.isLatestVersion()) diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java index bd846bb4..24036084 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerListOverlay.java @@ -23,7 +23,7 @@ public MwGuiMarkerListOverlay(GuiScreen parentScreen, MarkerManager markerManage ListY, // topIn (10 + parentScreen.height) - 20, // bottomIn parentScreen.width - 110 // left - ); + ); this.height = parentScreen.height - 20; diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java index 797e9015..c84863e5 100644 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -73,10 +73,10 @@ public UndergroundTexture(Mw mw, int textureSize, boolean linearScaling) this.setLinearScaling(false); this.textureSize = textureSize; this.textureChunks = textureSize >> 4; - this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; - this.pixels = new int[textureSize * textureSize]; - Arrays.fill(this.pixels, 0xff000000); - this.mw = mw; + this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; + this.pixels = new int[textureSize * textureSize]; + Arrays.fill(this.pixels, 0xff000000); + this.mw = mw; } public void clear() @@ -124,8 +124,8 @@ public int getLoadedChunkOffset(int cx, int cz) public void requestView(MapView view) { int cxMin = ((int) view.getMinX()) >> 4; - int czMin = ((int) view.getMinZ()) >> 4; - int cxMax = ((int) view.getMaxX()) >> 4; + int czMin = ((int) view.getMinZ()) >> 4; + int cxMax = ((int) view.getMaxX()) >> 4; int czMax = ((int) view.getMaxZ()) >> 4; for (int cz = czMin; cz <= czMax; cz++) { diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java index a106aecc..65294f91 100644 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -130,7 +130,7 @@ public ArrayList getChunksOverlay(int dim, double centerX, doub for (int z = limitMinZ; z <= limitMaxZ; z++) { - Random rnd = new Random((seed + x * x * 0x4c1906 + x * 0x5ac0db + (z * z * 0x4307a7L) + z * 0x5f24f) ^ 0x3ad8025f); + Random rnd = new Random((seed + (x * x * 0x4c1906) + (x * 0x5ac0db) + (z * z * 0x4307a7L) + (z * 0x5f24f)) ^ 0x3ad8025f); if (rnd.nextInt(10) == 0) { chunks.add(new ChunkOverlay(x, z)); diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 04c52900..437f35fb 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -515,7 +515,7 @@ public synchronized boolean write(RegionFileCache regionFileCache) return error; } - + public Long getCoordIntPair() { return ChunkCoordIntPair.chunkXZ2Int(this.x, this.z); diff --git a/src/main/java/mapwriter/tasks/SaveChunkTask.java b/src/main/java/mapwriter/tasks/SaveChunkTask.java index 5064e6d3..116d8ec6 100644 --- a/src/main/java/mapwriter/tasks/SaveChunkTask.java +++ b/src/main/java/mapwriter/tasks/SaveChunkTask.java @@ -4,7 +4,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import net.minecraft.world.ChunkCoordIntPair; import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; @@ -13,7 +12,7 @@ public class SaveChunkTask extends Task private MwChunk chunk; private RegionManager regionManager; private AtomicBoolean Running = new AtomicBoolean(); - private static Map chunksUpdating = new HashMap(); + private static HashMap chunksUpdating = new HashMap(); public SaveChunkTask(MwChunk chunk, RegionManager regionManager) { @@ -32,7 +31,7 @@ public void run() public void onComplete() { Long coords = this.chunk.getCoordIntPair(); - this.chunksUpdating.remove(coords,this); + SaveChunkTask.chunksUpdating.remove(coords); this.Running.set(false); } @@ -41,27 +40,27 @@ public boolean CheckForDuplicate() { Long coords = this.chunk.getCoordIntPair(); - if (!this.chunksUpdating.containsKey(coords)) + if (!SaveChunkTask.chunksUpdating.containsKey(coords)) { - this.chunksUpdating.put(coords, this); + SaveChunkTask.chunksUpdating.put(coords, this); return false; } else { - SaveChunkTask task2 = (SaveChunkTask) this.chunksUpdating.get(coords); + SaveChunkTask task2 = (SaveChunkTask) SaveChunkTask.chunksUpdating.get(coords); if (task2.Running.get() == false) { - task2.UpdateChunkData(this.chunk,this.regionManager); + task2.UpdateChunkData(this.chunk, this.regionManager); } else { - this.chunksUpdating.put(coords, this); + SaveChunkTask.chunksUpdating.put(coords, this); return false; } } return true; } - + public void UpdateChunkData(MwChunk chunk, RegionManager regionManager) { this.chunk = chunk; diff --git a/src/main/java/mapwriter/tasks/Task.java b/src/main/java/mapwriter/tasks/Task.java index 9aef1054..cc9fe2a2 100644 --- a/src/main/java/mapwriter/tasks/Task.java +++ b/src/main/java/mapwriter/tasks/Task.java @@ -17,9 +17,9 @@ public abstract class Task implements Runnable @Override public abstract void run(); - //returns false if the task has to be added to a new future - public abstract boolean CheckForDuplicate(); - + // returns false if the task has to be added to a new future + public abstract boolean CheckForDuplicate(); + // methods to access the tasks Future variable public final Future getFuture() { diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java index d0615ba9..af183e0f 100644 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -2,14 +2,13 @@ import java.util.HashMap; import java.util.Map; -import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; -import net.minecraft.world.ChunkCoordIntPair; import mapwriter.Mw; import mapwriter.map.MapTexture; import mapwriter.region.MwChunk; import mapwriter.region.RegionManager; +import net.minecraft.world.ChunkCoordIntPair; public class UpdateSurfaceChunksTask extends Task { @@ -43,7 +42,7 @@ public void run() public void onComplete() { Long coords = this.chunk.getCoordIntPair(); - this.chunksUpdating.remove(coords, this); + UpdateSurfaceChunksTask.chunksUpdating.remove(coords); this.Running.set(false); } @@ -57,21 +56,21 @@ public boolean CheckForDuplicate() { Long coords = ChunkCoordIntPair.chunkXZ2Int(this.chunk.x, this.chunk.z); - if (!this.chunksUpdating.containsKey(coords)) + if (!UpdateSurfaceChunksTask.chunksUpdating.containsKey(coords)) { - this.chunksUpdating.put(coords, this); + UpdateSurfaceChunksTask.chunksUpdating.put(coords, this); return false; } else { - UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask) this.chunksUpdating.get(coords); + UpdateSurfaceChunksTask task2 = (UpdateSurfaceChunksTask) UpdateSurfaceChunksTask.chunksUpdating.get(coords); if (task2.Running.get() == false) { task2.UpdateChunkData(this.chunk); } else { - this.chunksUpdating.put(coords, this); + UpdateSurfaceChunksTask.chunksUpdating.put(coords, this); return false; } } diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index ce871c60..e3ebb219 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -42,8 +42,8 @@ public final class Reference public static final ResourceLocation rightArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_text_right.png"); public static final HashSet PROTOCOLS = Sets.newHashSet(new String[] - { + { "http", "https" - }); + }); } diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index 4e241e17..ecaa7407 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -146,7 +146,7 @@ public static int getMaxTextureSize() /* * Drawing Methods - * + * * Note that EntityRenderer.setupOverlayRendering must be called before * drawing for the scene to appear correctly on the overlay. If these * functions are called from the hookUpdateCameraAndRender method of Mw this @@ -407,13 +407,13 @@ public static void disableStencil() * clear stencil buffer, with mask 0xff * GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); // draw stencil pattern * Render.setColour(0xffffffff); Render.drawCircle(x, y, r); - * + * * // re-enable drawing to colour and depth buffers GL11.glColorMask(true, * true, true, true); // probably shouldn't enable? -> * GL11.glDepthMask(true); // disable writing to stencil buffer * GL11.glStencilMask(0x00); // draw only when stencil buffer value == 1 * (inside circle) GL11.glStencilFunc(GL11.GL_EQUAL, 1, 0x01); } - * + * * public static void disableStencil() { * GL11.glDisable(GL11.GL_STENCIL_TEST); } */ diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index d330743e..581bc1f1 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -189,12 +189,12 @@ public static void openWebLink(URI p_175282_1_) Class oclass = Class.forName("java.awt.Desktop"); Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]); oclass.getMethod("browse", new Class[] - { - URI.class - }).invoke(object, new Object[] - { - p_175282_1_ - }); + { + URI.class + }).invoke(object, new Object[] + { + p_175282_1_ + }); } catch (Throwable throwable) { @@ -240,16 +240,16 @@ public static int getMaxWidth(String[] arr, String[] arr2) } private static int[] colours = new int[] - { - 0xff0000, - 0x00ff00, - 0x0000ff, - 0xffff00, - 0xff00ff, - 0x00ffff, - 0xff8000, - 0x8000ff - }; + { + 0xff0000, + 0x00ff00, + 0x0000ff, + 0xffff00, + 0xff00ff, + 0x00ffff, + 0xff8000, + 0x8000ff + }; // static so that current index is shared between all markers public static int colourIndex = 0; @@ -277,9 +277,9 @@ public static int getPrevColour() /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. - * + * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You may @@ -295,13 +295,13 @@ public static int getPrevColour() * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: * "Portions Copyrighted [year] [name of copyright owner]" - * + * * Contributor(s): - * + * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. - * + * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or @@ -312,27 +312,27 @@ public static int getPrevColour() * Version 2 code and therefore, elected the GPL Version 2 license, then the * option applies only if the new code is made subject to such option by the * copyright holder. - * + * * @since 4.37 - * + * * @author Jaroslav Tulach */ /* * Create a typesafe copy of a raw map. - * + * * @param rawMap an unchecked map - * + * * @param keyType the desired supertype of the keys - * + * * @param valueType the desired supertype of the values - * + * * @param strict true to throw a ClassCastException if the raw * map has an invalid key or value, false to skip over such map entries * (warnings may be logged) - * + * * @return a typed map guaranteed to contain only keys and values assignable * to the named types (or they may be null) - * + * * @throws ClassCastException if some key or value in the raw map was not * well-typed, and only if strict was true */ diff --git a/src/main/java/mapwriter/util/VersionCheck.java b/src/main/java/mapwriter/util/VersionCheck.java index 936a85a4..e49735d6 100644 --- a/src/main/java/mapwriter/util/VersionCheck.java +++ b/src/main/java/mapwriter/util/VersionCheck.java @@ -19,7 +19,8 @@ public class VersionCheck implements Runnable /** * @author jabelar * @link - * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710-making + * http://jabelarminecraft.blogspot.nl/p/minecraft-forge-1721710- + * making * -mod.html */ From 6916ea3528f4fbd9f2e9b872bd419617e03489c9 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 25 Oct 2015 13:41:03 +0100 Subject: [PATCH 089/109] switched to latest forge version --- .gitignore | 32 ++++++++++-------- build.gradle | 40 ++++++++++++----------- build.properties | 4 +-- gradle/wrapper/gradle-wrapper.jar | Bin 51017 -> 52271 bytes gradle/wrapper/gradle-wrapper.properties | 4 +-- 5 files changed, 43 insertions(+), 37 deletions(-) diff --git a/.gitignore b/.gitignore index 0d14d550..fe3cbb07 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,23 @@ -.gradle -build +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea out -classes -*.iml *.ipr *.iws -runtime -.classpath -.project -.settings -bin -Build.bat -Clean.bat -Deploy.bat -FixDependicies.bat -Install Forge.bat +*.iml +.idea + +# gradle +build +.gradle + +# other eclipse +run /Run.bat diff --git a/build.gradle b/build.gradle index 2626d162..f1a853d3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,22 +1,25 @@ +/* +// For those who want the bleeding edge buildscript { repositories { - mavenCentral() + jcenter() maven { name = "forge" url = "http://files.minecraftforge.net/maven" } - maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" - } } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath 'net.minecraftforge.gradle:ForgeGradle:2.0-SNAPSHOT' } } +apply plugin: 'net.minecraftforge.gradle.forge' +*/ -apply plugin: 'forge' -apply plugin: 'curseforge' +// for people who want stable +plugins { + id "net.minecraftforge.gradle.forge" version "2.0.1" + id 'com.matthewprenger.cursegradle' version '1.0.1' +} repositories { mavenLocal() @@ -77,14 +80,9 @@ jar { //classifier = 'universal' } -task sourceJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'src' -} - task devJar(type: Jar) { -from sourceSets.main.output -classifier = 'dev' + from sourceSets.main.output + classifier = 'dev' } artifacts { @@ -118,8 +116,12 @@ gradle.taskGraph.whenReady { taskGraph -> } } -curse { - projectId = config.curse_project_id - apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : '' +curseforge { + apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : '' + project { + //changelogType = "text" + id = config.curse_project_id + changelog = "" // A file can also be set using: changelog = file('changelog.txt') releaseType = config.release_type -} \ No newline at end of file + } +} diff --git a/build.properties b/build.properties index 3d1197df..22e7fbf5 100644 --- a/build.properties +++ b/build.properties @@ -1,8 +1,8 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 -forge_version=11.14.3.1450 +forge_version=11.14.3.1521 mcp_version=snapshot_20150615 mod_version=2.2.10 curse_project_id=231387 -release_type=beta \ No newline at end of file +release_type=release \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b7612167031001b7b84baf2a959e8ea8ad03c011..30d399d8d2bf522ff5de94bf434a7cc43a9a74b5 100644 GIT binary patch delta 22968 zcmZ6yV{{;0(=HrNY}>Y-Ol%ty+ji1%Cbn(co;VZRwmtDA=YHSeISM9aB zcdgymuB+;IEO=cyIHHm)I0P&R2sAVZzWk{~0wM*>f8+pI>!wfwzXs-6#=Y~MGbqUa zaw{c<_}6`$>c8?2)4wu_8g%#H_~Gr)W%MKzFk2ud0)|DtQeIBT&IsJ1*2B~x;lA!M z%8vaG>ZK^U>3a$>DB8{7^d+l54b3KJLu?E>r>fTS zH36D#yA3Jg=&#m5ANb!``nwfB!rE2&O{EqGN)5FteF8lf1b8s-8HAo_j8_J~JtK8I zKKcXba^Pcx+W~6~y+n<`bgo?m17_AizCaYF4u8S!PeQU~jGVj~i4Jio% zf4x$Wtj8@>`>wU===Ze&QT}-XLOjob`gdT^Z0xTF4`}stHi)SE_eZZ;=Wsvl`M2D# ztv7gG1wVRmX(mhcNFW?LS6=!<(%PL>f>ce*#zi|NG3jTBDt{%*VOcYG<=KUPh7%xH zJ!fDp3^)xv*36UX6z0gL>Z4<}&LF?bDZp#%Bn1HtAPbAK_6ka6E%QE{kwBuGaI{iv0y|A3ZKWg@EaYUdUY zz-j(oKP*um!bopdz+78o`Zs0J{=d{Zxzuv01OWlr07)v4z)i|*M@(vkX#O{Cn(QHq z!2YXYK%;*9uSSPh_CK~|WF|4 zp-Jx!^GfKWeQBe#bu1%}a_ML}u;Q9w4lI;mrZ6Z(Fy@r+HOX1EvQ`D?F<+5DDDLnO z(FgcPQS?bG0;*P1d~UAG4Nu+!E%5pIhOmpQm?X7p4wmLf7r0SQsT@o%_Twj?$YzQo zv2eny;m^3TZyq?nD$L+I+aT-a34Fu3^i{gPozE|v#vgN$Lh;KhS>>#XkQnyD zr)$6Rk>(|QgjxE9t+KX5z?jX~F$OfbIHoGJ3OJ$we4sDtAk(kA$w;w%X?^qsbRoS8 zB=2yioA^0{7&6yI6QDXpj3$rM@2An<(>yG+bVD^^^vR^Qf+ze}@pF-OMK(&dNpo8z zbrxkk8M@Qv;peS+L+3fDi*e>X`*~CFJpKmaYwqWwgekf#n7)|N~=;!qunlv)zrPwDy+BL*pNBU-gI_V z4TU+QQ9t`ZfF-|w!_uJ{Y6kT`j05Xk`=Q%PyYK|n!*ye|J;}wklhyY1IrEnbG<&3P zpF47ZFnd@9|C{{~O%JiCa@Y~I+*+$?1L`mkL>mc`;Ld+acJn}gkpH~M_**Y89XMl^IQ%Hu^9*#(OjtrZ36 zIE^{#ZD>(T#UY z;0v$u8!knbJyLqiZ0P7Zb8==kOZ+8TW=O4{e>gFd*Hg7TwB;Tl0C|(kUaNkF1ulvTP@ev0M8h$B6(v$axGC z@qW+qnk64Br{xOYW>YLCn`u;vxPR8UFY9mnWGQwz|;HjE5qN(K$>4ZyQ7}|a5ah)4O`!1@YM3~(u z^Hj)~W%`DQ_~$na29~4puopk!aGVWe&jpE|%2Sf<^Xr0_&8 zyP_w~((5Q{;9B&O6S;GM)csN<8Ygili2)4csaGGUV*vdI7|ouNsb`FQhUm_vRag*z zYziGg>)`eqgM!`C^Yd#u`LtPom}u`jS-j_~(;g?49#N)AZ5A8VCT|ui<_I?YFp{9& z9Nbac91V-?la;uR>H?0}zg6rbbW1x!kHrTb?$=p z760g1R&yljvhH*s5N-N|G#tVw6@IPWzz$}dB+yG`|x)D;>My4#rM!TO2c6Lv^Q9x z=ht^{4RJYdKo3}nmyK+j2i09xFJvB^Pxzx!*+!u|uDFA;Mjd=?^Nu@oNi^^O^@Ojc z)kGL`^t0dSOcQd~7-zX|m~;Lh){Jx1;0|BFpsw?-B-+P5fp;Yyx@q#4sjLeDg?GjT z7Yz)gDyQjmVu_#bjt#3!@e6?@w>si}%3o-5U0p$>j{wN)A%>XkUOB&H6_uyk7BX0I z>7ZjueQ2TMN_^Nb#HK?zk#myzj4>|PzWde&QPwW9K2bh7St2-5n*fkgCj(iXQ0}Lc z?x)@=ihq<$!J$s(Yxb6)n_nJutSca848;Gp%jZ&fJg4NA6MY=A7w_&e18J*(v z`enx&FaZR9H#9{R>qG4%#dQ<8DdInp=|Rj_m&4R0&>XLukiXme0g>#ul8E|-Xi*G& zLRoy6zQ7`vn2d@JrJF^8=Gv9yYj#=p5z&+01sZwm>H&_26!cz@09B zDynx>yXV_k>ZE1C`6lSQD!M~#00}y8 zvxr&PVv35C=5#Ld{v(9#B4gxszTxhfnka3MfYa55pKDL`m$YN%!;QOsIuK9WTIX|2BA z+TChIII|#$9iH!{r|ji7)Tb7@!yWjQ=B2>OnkpZzQcr8aNv@Rbb7I$lt=RFF@yZbd8DE1Nj>Jd|Kvgg3-j33Q7OAh>zZ z8Vyfr@kJm1`d^obf;ItdEF=&RJCYr3#8rD}=TP*^I82Q&VA+mIa` zjxLrtnzUiaFSu{~^RdPKRXKkyt0|1A+)+_Coc77t1svBY-45m{?eS2_GRD#$ofjVE zlD6#^mLoPw<$<1?u#disttA;9`1`oLZJ&qj=iYbEo%@y>;FW`PeHtqWy^PEB#Rb6m z6bW-kF@BN7`IHg-;*~P;RxNPw`PuiHLYy-1ad^pq^GPWM$O2f!H}gACXE1M2IK5@F zLf>e_zR2^xs%QI>=lbURXdZ7s-;hE-*`(Ya4TLL;zf%8x!OVV*e*mz5fq2gOEaA%h zn+Zp7aJ1?4e#kV4RWd&PP(RpraG)B3n;5S|xbi3;-b`4-D`VhD*t&!Zyc?gb4mmxg z5f;)5qfVn;WRC+(8>g7BgI3Cir}}oCxCQR6$5%37WiNPT0$IgVG@jS1Xdr>u?O_DO z0rvJ7!~w>cVbGc@&mGh2#Mj$yjF0Nb#c&xcV>B~xHILE+*+ z6sEtsV>NUzl)1fGBM)D}bbh4h4V0|F10Lz(%r!4{5r11J(&)6~3^M zkS7Jb4jxRcUGr{BXwA5$rR{g}2osi!o{KJ73(MHlJi*;!))k{Nj@%n?Dec^lfQ;BD zcEAzEc_nN{l{;d5E4FWgCyW3yH4_oLWDHPkN89LuYs*-)WQD-W?LIP(MQ1|t29Qpwm$-FVs1QxBlFk@y z;d0Ge&GBR#lC+wLphBs?{+*s2`)Pl6N7jkyQN(FCIt72JqWt|Wz$(V3^$Nrj?I-K5 zGy;hUI`&1qnaqcWd2~orgevo^F$mAx!)d?BqtdqG)6vx4=1)rD`SD^~0exsxSHGux z9z_0$%{WFEUqDZml%ulUNXL&jgdO4t_v}CdH3Ln>$NECy`**gjy5Cdt?YXlQ12v?X zVEKvD+&Bmy`%wrl{kPa5O|IPQl}W>iT~v%?z8Qx+-~$fy=WC%Ow`bBDnd2LSa~!p; z#39~?V#cr|Qf9XCvn@_e2l$DiknbYvBxf-fiFN4xHh@&TCZ^%FwE4&%Uwh^0qy1)Q zmOs^1j6|HOs&l5Ge~)=GV4t2bPR9SV9rBw{ov>VaW&&eQBENFQj_=9E`h=(E{M>A8 z=u{o%9atB);mfP(! z;+@;wVSw7wl3iXF53e@8?KV?UbZ;NTrCf>!k~FBvXpZVG!YcE}ii739mq#RooZ;4Sa9=fSBDGg+A`4zORm#TZ1!5zKksTZ;TA^Pohf6#+SM~IE zGJu}e5!$0yisF4RZC>J%m0;2QiI`1430a1Ecl{f(%Gng{JU`0TVgLj`Kc{`6wdd3I zc1`1mXpouK5%(ZF8EstTZVKGZ5sSn(SG@VdNC$EbO+PZS(j`n~uV{pn888;1Nl{oT zH9`wlLYqh|Lw0m=))Jpm=S2BECW=9_2f#IjX_i(udf>7~dWC#A=nQ}LL!_#a!4Pk| zcbRp`BO^m>)2aTEK}`IbKYO-?9e*f#3{97xBp5n95}Pc6h7B#_`wE$0JZQ8)sbu3P zJ9g+hjd>?eL}Rt1#F3AH$bHH+RZ%$^(xBK!c^HrD@1|mt;1ZaYndVX0PCo3^nytkp`43?=ciR-P-vj> zqMaf%umuaK9i6)fy{kgrN4A3+sH`1O@*;U%#B+rs&Jp>u5o!@ZJ+2q}gJ)DVRe{wPGIJP-bx}>TJC=<`SAKuOJ}UOLLGt<$0-3ZlYdmdxu?~ zZoL~@v-P#UBFwJ|J#s1B&&c5bz9zGD$)F&T>99i=JmaS|3$U!p!x1nj;kbF}*t#>E zcVdf`Q#AT3I8Nu($s36|c|pUQsfQ@LrWD#QU|KY_<>gtp+V_!U^A7Bj=6fO6xb>a7 z3Vy`<1)llX#*S;sGBa*frFLa>Xl3^bHU0xTVz-Em#cAvX_YWv=fY+znf3M+$){eTM zS}YgLZzt{!8ek{`J+()^$1h^^&i}si*Q?@-E= z!=Ji0kZ~4i&mY6CNO2xXw40CkG0u>p^lA)lJpqFq#FkWFTA$zJgy-_3`~X`hOsKiD zw*Lh|iDvjy*YQ0w>ad4j7Na3-b{S`VdGv3S8s39JQD-`pnh^3s816UY-VrNn{PcoS zPKQ-Kd0@(}x85OBC%25jQR<7nMMQf;l&{o^3dF-Gvvg~r`2>|9y`-l>yOWLb)?-R( z1OCcpFw|YIy-ObD&sAItq<-0WJ!||Fe;{!EyF~KyV=k;~FFV#HN`d zuyCQKDfRJ7WZxOP6DevUz9&e(IIl#(;uF=)0uVi7S2xBFenPOkG|~y(t^TfcE!Jo$ z+IcEgi5)aT3G$b``IBBFPolk7N)cqkrF`Ax?u` z3*VvSG)`W@P1QvM5j4OA`4>{f*9BhDL*RtExq_je%#Ismag50ZfCcKqA| zAHV|W9A4W_6HQ*#9}yg#w-atJ9$kJ>A;x@i;$>3ZQkKh=3&nzeO)s_26rB0|6I0joJ?os{*;=m;{F6g87ZBKny?Ho%=yu&EYXF-Sb&<0T6M;slAf{A@ z7_tr#K?o`!44nOWL*Td{oz&sGs(FfK1j3|MSvmoYgmi6N!ZbiUaKGK%`7}Qf+bMHc zM##1N3aXSy+|Dc;ZX%`k+?DGlcE1vE$OIl$6s^X7+WFoPrACv;K0fL+#ww5W3y|$& zk!5LriCFD!!r|o+MQVM$7}Q_m#dw;TwQ_o9OS8&}PKS8b*KFZkKfEXh)QssrRz0XQD4IWLMvQBCL0(Vtm-4tKe#8V&B6I zG}mFC2z^jBp3xp@hG<@d$m~kUpo1bUiqzZZC~^=(=Q{38F_Pu?u+vV6^yOy-_?N}l zW+J34GU1MRsf5SwuQ{aub)jxbp@)O~FL_eT5(@h-WfFp0T-EpwzbAqX0z&(5ty+m6 z2Y~WKAI12DQdnQGR_BH(9!v&@Ta2F$h-vtRtc^+>kDPBFXxE*Md3JlIv3aGupK4sT z8nGbNki;#Zu#cY2O|=#&e~C_|;Ng8Ub=Jf8YT@C=yTu@4(2F#6)$R4S$Lj_`QSjlm z2xK`bhPHK&5d-g*wWC{)u}{Bq|F>7b-c z*)V=9;pJHu$+b5HyIoi~589_bjMy!I@7txfO_JtO*^YFha%&HHb9dkm<6Redu`1p3ZK+thsVc9d^_2=!7$^wsS{y%gyA7w?b0L`3H8 zTfq9)79#Z_m#=%}xAasUI06o%K;U4PcPAg>^X0|G>!JPAnJ7s>fFm1 zW?&*GTW<4XJ4gPgO4xVmxbB{!x|XJ@B7woO0r9n+owd2NK*lV{DKgqk+!)CkJ21G5 zb0`R3yJO~(6gTmMk?qA*6tcN8q6i!nX|}@AZ;xVX*FW-SaAPPTm)$cWfP`Bq5u#X} zy(Abv-%Y6ykM#{4e%ZcL>g(_Mc;zE=dJa18Pl zvILiv9Ka-nYb;91{0vBBmah_!*&J{ZNML_y;MJXxqQ|vo8y$Iksb_c3ixHI&M`801 ziYD(j>wxGfOG;&FWg?@E0)#i%alELH+cC^O_{G+p!gP@x$zt(5l~h~O^Mj|k z^LD>gTr#>uyJL<_CZJSYit8(%HX=!D9*giQ;3OoQq4tfy0gjxhu0Ep`KUwS)LIwG= zFTev++?tA5e5k;yc#ZL6G!OGvPDY#)s^nXv?>qU~h4m*03^(fsfWJ_@K8m9Zf7K+6 z_FqiobYF9%aj?`o=P}p}$rCvxj+&#ht2_sU9k0RFrLm>iQhs9BNbh66rT^NGw$Hh{ zOFjyat|X8aHyMPA{)s}+#%js=Zp*;6_=8*iesV{Usj$OY)L@p>Y$8*YOh(z^ZI ziZymW1FrpuJZ|hBC7@9R_k$dvZ)m|)y_OG$<1>Y?Sf0k1GlrFh{R6g7;}#F0Z}{e? zi(dY&C$06Y1>RR2UHRVgOK_Obz9Q^r^&Zm;U6S>&$klvO(bijgSl`|a?mvXIwbVW$ zLfM@y0_L^aEfd1m2mq1l-Cn15yq)0b_F!4RQ0tTZcwnsTGgvKTKk?NUM! zlt=$5B2OJ%eyhr%9I~M$QESwW#sN0GMlOOeoTy;Zk**k{DHcH~Bc4Gz&e0$Rfv#K- zA=99RBFnB!0aTtf^IX&Y6-Z)&QgNc=H8({p!4(##Um6luG1yVgtcWl(?)cTpDL}|o zGg~k05zT@kl8~M&7rW3@P-ISeSczwR0!<*FZc+f9wTU8N6=JtAc z=_u3HNAPdzpha#BQzqkckky0^@LGE9RwATpOYbf=)*q zvL<-wbLA0kg%K;t@pf8hX}g@_)oITMn7n)4!(u89@mD06Y>H2#4nH4oALY1WGCSX1 z*|$X&fTd^WnL9&7Oo0VA*Vx9z16C%&rKFmOgvE4}HpXI|u)1uRSP4lL82xGvFEg$k z?6rH?%LdRU!fvtvnD9GU)6NuVO$)d6Sf${bdK?|nv^5iAj zD*b#$thABZ-dk#6GcPPC7rrjl8h0NBi0!fT-`>qwEl>1yiC`?cYgP#o(B zktXB^7nMn!2Fn&AzoLb@zixo>s>Uoycz5H7YREzi|4eshD8tGALl@r!BmyD5OVF?kvw+Gmw6=qF7 zKu9IifD_y<>1wDUVOiT2xf<@O^dVDQzz-@Z`Uk0X4&uqa(q&`^3%<};TN+#9-CF9X z+i~(o<&4J&tfaz^j0!F`E{=uSho=f%DY|^DA-D;O5u-Ev}=-wD*>K#xX*L(@4R!;a?C9zzDn* z^p@o3Kg^0)Z)O)H^}au~O`S8qY-2F+x1idOh9<;!*|8@!p82pH0i9j$JHKHO{;`fF zxaO{RZDueCf#i#B2y|G4xUo~%ek6>KFDhIoE>%N)R+PgHI&2uF(&|3k+q}}Z;NBp~ zT_PQ9>T`m7$i;2;$c0(+UljlRe`))JRjJ9$ykv#zzt1zmzTwV8H=`>Q7K+2rhF~fb zBvMB$XeCOh$5SmaeCGFAp$d0sud6gOYOzN|=`7~2Gl!aq_7~F7pWte-M5LfW%Ns2z z%?brBp|yL$avZi$#CJ6OTy^~)o=&X-C^t4-Nf(_l5Q*W`NrMz@W{kr?vaSSQi$FY6QveuN%1@% zd>i`NLNv+}#@*vD&|{w{OTwckYY7Hx*5X7>5Slm7c{i6z+Qznc0inQ3T4u`ww)Jsb zHI3jJ(v5lBmfD*wa-}4i57>kKNy-nd(o-_Qv>YKRQG>UXgycOSB@I?He$;1~1IGm;Fo2#@EUONf?)<7Z zQY8hmW62GQEuPNmEMLSGn&&c)X2vp%p4)P&y26g$wRK|a1H|Q%-ink2jV7bC7 zF96BBTl07PR^&;1Z?^P<9)Fx;pD#mKr{EMa=B-CS=ePBF%bkT=2pL;HUVI97W;YLa z4wa-IF@e+U?jChnBfu&d%ktHcvgX1XrdN1pP_K*6Wm8Z0sldsYA4ThI|NL*eC#L$G z-#b$`TTgW+GvD6OK4=S%Dd<7f<%(0}hH*<>$o%k1)9MTt+nDV<*o>Z;wM$|Ul4qr4 z9m=j6Wm@(jJxTWHVEj;$w2+(92|XJKipZ}WueL4982_#!Q|rl?>}-|0CZ=TlwZe}V z%oDqjJIuLkrX~q3k^9Pk*D^A|`@J=g!}vVK_&iVZm|z7%A(t=26=y%WuX65;(rt}; zQSt@;|8`~U*E*UaeFFjc=e8%o29UEv<2uoyr)aE)8A3;{!&-`eFOg6~R;sEIWeuA% zqRf%|Zg*vDV}sS@ul$iz8zYx<6J zG1OeVRjUmaZzusUx9>ok@M=hGVN+&ONl7vizA+v8;2 zOM=7mo;hYR@aiC7&SggB8dz(<#;B{Nrw zh7pDpv=3X{N(Y*`m4StyrS!5KmyUR5k%8!N8z!aI<>$8g)5mSOOXVR15^7vYnJ7Co z>%r!e!4_ux;V!H>eQvDF#N4e`$;8yADePPXzIBHRLQs*Djt$%aJ zVVQM@q*ciLIflWhyX{25GVP9BG3}l{L^$q=XoHZsK#Me+@C35fZgzh}rdFZx)R-&Y zc-{6!E9)iSfeJqElHm{?pyA~0v*F|&z#;V}-(mDV?IuP$tj@IkoNchybXzi~TBJ{w zSl|`E?j3wi&eK0=PL-;U9@n$WB7Xr*6L?V`QN&Ji3himW6|6G1(X!4OFovm4Z_x>{ z88>a@gP?UF3I}c_7}Oh<+^tyy<;CON`q)}CMpzhf3st}CXIbErY6c)Ze6(BNsAH!t zkPzy4(1=f(vv?aru))t=E-)gs=bCyCdOVxB@MGmatHm;4Zg$dI-bwPqW+bW%J7`=&j@8% z71%41q`w4CT3Ti-u3aBZeR)1n`#jHT%ojq}FVEwv9^yRFhL+2V@0#BEtuIx|f=RNY zCQ8!o6#&)mP*c+|{K-G?Z0uO+3s3EVFFXj5y+Wfnf;4&l;$ITgR96V>Hj*$hR@Ly!F`^JF(M9CgxZ!kK zBr&3}`l4qTiK&KU%3Ny!-P?+4)01>}AesFJh=A*RBBmGp85Lk}oYMvR+`l_REj{Q0 zz8$>6Jfr&K0&4B-`k1ly6(f^4juta+9cA(?KrEG*(NV|AtS!MvPH{)?W2BFVu%=xpPHK>-0FG z$tSB>z*EI-Xd2^1l!|KiJz(7sjYA|P(k)%a zD_O=fmm6y~WI}B+OKp7Tj@aIa?o*_S8W`nN4&`isy)q`^9a6qT=5&u_J4Lr>pj&|7 zdW`YUwQW@z>=>(zJtnaZ7OLoJEyO@=6Kz!o+lOvVP}{997uPKXb=afjttVi-?}p}+ zqBXK;{f)0p_3HPN8`a7ERTsu&$coF_KEY~u-VisiLEF299nNqbVQvfOFXQF!XnLOp zCbA0&Bnt4`1Pun(KHz_~@L3aE$2Wt5fM|e&fN=j$2OmO`c{g?vk30fU<qu(Nj~aJreEo{K|o{o}(`iG3moIlqVO>7Ln*lgd^z8%uVPqUxQb z!Tw(ekZ2-8u`}fwtpD~rMB8q&+ehOftR3KEH1t_~f1VoJ^zuc>v@u_YYMwlhAr_p1DmXTwSvRYDab8&`EBj z5EgP&J^L3ptzZaJ)G?XyOfW6sfTWqP+{map`vDql=B+da(t)b+>jEsH@;~(_4fZ_M zJ1<}1VXQlfIey&2t5I}c?P1N^_UJm=m(0ki7jKa58L_S)hjLG_9kn}#Y_)n-xn73o zY}7~ZpTLH)&&0BB)Qt|goLFB?qLUfrKKiR=3DzR`>MyXMpx!WiUJ`BMf zTC5HIWm`?QQ5VkO-swxkUN@gZx;}Le&iR_8uht>vwwSOB1w{V~-k(Nek6_w$e1@85)N408n>k(Y+2~z|nIc>!f z+rfgHk@Xre5;Jc55&AXz>ZO$YYrb4|XXCkqJ2aT7344=Lo7K`>Gk!0=u7O)_4!nn0 zBc!qz)YHiiTYr0nfD1nUf%wUffn<^ahw(KH9WgHJqflj)V@4gI<-Rtg)tNuZi!03| z!&}rK-%ZG6$a7`IlVU=Sj3(#^(ID)i#_Vspb`2pV_itYfkC?L~YKrO@_obo)nSk*} z<>4@#K{=S(I$8x8S%#Dn*bVwJsoD4=HMsDrL;jfIn(iESu}Uw=RGe9+OUu5z~a$z$&hTcN0? z85Gc_tPL4+#$3m8E9;SIFc1^vs4y7GX&-M{%yUsR_? zX38&HS_Ldx)HUZfc_i1ABHV`S{@#WKoKx5JqMYgY=M8m^Lxd_NN9QN%Gx`Gt1cw7! zj5=^;qlzW~w~F4OlaQ~KsciZ|H>I=EG7{dHcRoyae+~vlx5$mwq{n7axoum6^cGfK z_m#KqrMf(J@0#QI(Ki*#%|yMwYVBlgw(@nTydH&-(8m&ri`uw~nZ*Cc;NJj39howkEKmykA^W-EK9$7Vs(V;?vFlXheU8*{R z-C7C|xV*w7a+7FkCESF!n44}t%$jT-GA0f9)@x6#XwEQN-lMG_A8kC{h~-LX^^J#cziT#Jm#44Bx);jm&To&KUXVp!===}p^;(pl z?I^cP$I6Vq-!p3Qb#BwG+jFkCsK<`>3k@ugeOJBJ?+zYh%jNWJ9#Rh(V>yZ|(TqsY zo=e3?*;|F9I8v`*^e#y&wC;cxB!37XNU{FV2CuUDj`3N{mg;|>k z)B&^vLr|M<;u0%}<0wEo2PxJp<{ehOJ@ag1&1)fRd5C*O!gnzmLqB7Sv1fA184{IW zVN|nk{G4G9)P@U?whAF_^aX!avet0{Z>^n@)(RV^1Ci4^Rm&@Xl-^r;$W7l_G~BMm z-kc!p>mGb}WQfK@uA9oPdDX z@j|@z0&g8;?lf2}5LB?Vo!k zKS}z#Hxt5lH(85bD!+auL+T6gY|m2brP>^HC*7QIpC!6R`$4?P)M@DX-PQRe)%?iJ zR*_w)iX`{;c?c~~iZ~ZqBIqszKj8qTge%t)@u`8tZvW&q_GG-`<`#c?_O3@x7>t2` z+ndl04yhw$^zwj2EV48*Fa;5R_Z(lfUs1qqVSCut2<*5gil){fj7*5HCVH3p3#^$# ztXv{}TM#q1I!&JlvzuE^gh3`MZuSNw6XR`N_}9|c{{<%S{+TseiiQA^+%?1q6y=p~ zX{VH#>y?=6n^{@vSvk}l-4PI#nOT|HkCIk2Xb@ojaR(b2vY7g3G6^>cL6ZdNvIi$Y zzI@gsErJXpft2r*`llJhii|LeZ5fnmSK;*|+r+0UBWEq+k4@%*)l_aKLksc?-CYLj zpS^oyNas*o1Z%5e{{cVZ#q0&oC`^N5L0Te_WHBA+NEv4}iNwOOygSQiHepZh6~V{} zQ!=}3`KjRyEjzU0Pvy<|8Mjp(A})`hsEtjmmR#$GY^$&x>inmLrH|b4x31t(eO5*s z!em}Kwek`W*(xm9!EMz1(07Y^ck3@m3CAu^$5net{U20x>E63tMi!s{7svRY_e}bx zMF;U8rHMl;9PD2$>6gywe@)f8pZ_&A)#{)AkCtha2>Rcr%qE1;DE|q?x4~?f`e%%5 zA=vc^0(YtzPZ;^E zXGPQjr9A!yjgz#a4lJ4tsbaiE^4wU2u8eHKY-mXdWM--#TU1~%I}D{zD%Z>1G@e8E zttN6W9~-XhayttX+sQW1GvA4?MaR6*=liG-_zUy4Vm?|JJX;`gH0GglsuN9MInY%< zR75(ckUzXtLD>*8A+6Wn==l%!(#FY?&Bu@c+qlz1%^NktnW4G^>qQ=oV(m@eZD699 zjZHK4F=D^N6+QxSEZ$g9=zXMVR?hcIE5wF(Pisa7X5Bq_!~ za?4DbBQlur*I2R@22@n44z*SA1BKtM(^92nD2$7fG6$?`XF-lLeQY!ek9uo!r1|Q# zM#rmZYNTjY}XzDrRHqJ>Ny^l1-XE5O+w8*?6J zA18e}xlEH?&mk*dFfZ{oE%j3_9a7$N=GMG2>V)G0=1yM3dpuiH)tteZF3=R@sUBJMegY4Ma3YLztP!T8NMAw`$Y9JlPs3p(e|!FD#G53=~(u6$U2} zxw2~9#hYoCLtj_9cUa4wTJt&df;btmWT=(Yd-#bOwI5(wC>` z2waVE+C0u>EkiC7LxUi zA$q&v@?b>JtvL8^9SCAeg&W>bEf^f{r(qq5wd#t0P1jbMJETE27Df7n`HNC3*C`*H z^onG!pE1u@paI_R&(}v^KuA@)Xp4DWnbk5x{=&*owRX#Ki%F;DZ7k)>-vKMg@H@UI@-ITg@z#SK$f86EnT+*5;b=SIO?_b7q7kcc_Xn_zvQhljwVKTu!otiX8%89 zT#!P)kSI*AkGa@dIW*8epoLQJ&^U)AuFXEw`e$xkV4!-OxU$re9g_J|-C3(C2e z$!+~6dOZ_u2O!`f*l1A1a4)<&w&HYqQOyRgLN4g2MX;dHwkrBFkG)M5rcPukYZ3Xz z1lvATQ3yKVwpK=+dO!>jL)#){7Q=T_pRQuLQd3W=9jqRBDbVkE7BK76Dm%&&A>C?P zQvqU<@t6ciFu{7Ew0^lJUU+_5fzn>+ZxZNE#2kf(~8i zo$n#W$;Ox84&7K38bXctza{>)Q6iT+S*e#FP|q%oPrTK%&FhHKIB!Of{AN$u6Xrt> zFWFU?t1lrHYy9p=|13!QqoH;T*FD6^{b;&RHW5uyNel08wmPKUZg z%l3xmG`XOVP!h1v4z(kH1=QLgMnlgFtRDc}*O}+fo6r$X$L26!dwe6$XB(%KZO;ml zBYL0VWI+PqYoa3e=`q*dP!Yawy;-YnoO#<<-JOMQRky3-IejM%`=2&~TkkpJr=s{g zC?w77b8ws*#QJ68NlS1FCtG3&mRTI48jG z1v!zQr=xceR&XmQ^v%;R5P2m-!j~w%L42gbb{(HtW7!y&tZz^vT7RtMxM2r!B=JXi zH^F<+>?WVF_sFx~K~_DPFUgG*w;`XT`Hzmy<$EE){UA0}S4g&65UuilH?R?QM_QV? z{j(2)RsOKNQibJZ_9_kG4Df5AxAN`g1z2YdUygp)_Z!SVb*GAz?nAc%Wj8#1=qJ_@}WP z8d)O2?2q0~{4ZA7caa$q{+@WB+Or4@lDyJydBrld{d&lLXL`B5+Nbtgr74B*>C=!C?VS*fEg}`AfO5G5 z{{O*uQ`(w4@o!0u=;gB*{ON34rrdTWZm#d*Dt=0w+%Z3Faq7 z`fZX3A`)=RDyEhU!3-T1?kS~^82DQ*Jp)9!yl|2Bk8)L^p`T_&jfS}NPvz>G8)LgF zzb!%Ao2x(Dx*I+YJ{#UPx@Ub)85xsuh?GwU2bTgqbv?`L7k4);9@`%;9cW_gQHsa& zh;P8_2Ous;^!ua^_b)@*rvlN%VSy^|mEn9vg!cbw<0`Ma*z1hhIVVH`l+P+a*R0nUasWOTA(EFir|W%;WASS z!4DAqs|jn#S7V<`##rcfmjzdkZ=K#FgWnZ5=|K1y|HW+CX9KpU(t?m|d zh27?lTp@{8bIX5vnE@J%gDz7o(XKT}9Fkh(7n| zpnIKWh1g+5RwlhsU4@{r1f7(<$1Jm;SC}34ZZR*_1#P;SHKS`F_lpIeO~M^N-tK_~ z?k%WuCx>&+o2E27NQ~90b;0?2n1(=m;;5AD&zg&saiqv7t|{l5+6(1+%H2>X(f3Rn?AG)JCuz3(vC-!!52dn>)x?U(tu#i#SzU8M{aOJM z`vRNDBp$|sd@-^@)h&B-e!DOIyvD#(3=0mjFFN$I_Ejt&yE>^$(S=eM`98wPs`XPe z3%+PKzaZlvq@FGhis2Hflm>V5>!(5P%X8+(rBX&E8YxixwPQkthqbJhV9c7enK0`X zL!l;&TLrEcuQnX5lE>EMW*)S#N}L`wjdpBpH`8t9v~wSYqRbxtqj*b zmz(6fhi~aX>NJ(u1i`8iw>QjHJz3G zFCaKbzf)keXcYdeO)QZ)GBoUwch2LXEJy{u`azCQc69|Qv4bT!$$YpO!@;^rWfz@E0j<)7VLr>uvu&8b|NPlHw4P!7S;(^HY16Djq(F>U5;#sLrnvT2 z`uosc*>?)G-$i@Pocx_ZP-ek5q0Xs9g#nWjPj)PllI-P>`{(1TGR9u>xK4+TL6&R1 zcSd>;%i_n?Dn!K9xh(d6CM;y-NpE{nsyA z5N@4b&l>ltYPd!>K1t=h!SGsLPI`giW3=Jp?-ni<&Bw!HlF zC|9Lq%?_NGuc$gRAHqN&SIRm25xM%YbiNUL%sDv^foP4NrW545TkwwTxGzs4M?@V) z2x|w@I~qypy&p&)1BkGMJu|3md)SdYR|H8;9YOc zG3WcRLe_bMcE2eA?1lKo1k}Pht-T`3;Dc|?RR*A<_jQv8-jAw`FLY!cd~P$K#;a06 zrmDCR!ul3`kbmfcb}1DkTRlJ*3^HavI(&N<_{O9#W!hia_;xOoVAt4T5%dcO(Jz;< zp)--Tu=+QrEG|@O4g>}zTHsf_psrPqaBE>p>%sRAY)PH91deyi6vb&f4pFo1Z>ha& z)A*@HWt10vXV5`R0O}78Am$KWk3ZlJdId*ITeQTN?$&@=&psQ`sGC|?HW<*#32*Zw zaoX7^+gOZht$<7~tes#6ou7JPCl)sz0D+vk#(&}BNi$lDc2h+Q`D?DX1Te7{-9ewO zPGlr&FrgJK)Cv)`;q%$-63p(gAj5jrWr2-7^2ua2kcq*rN*hkW7m?Uv{iBA3+UEO5 zM^O?!VIxBroY~s;ejz@)a*}paK4FJs|n7NJfMp2k05T;3XOuX8WRlB##;5R1z{+Zi_WRFJ1)(g zrUY0Y<+Lc{W5G4{??5~}9mUuCp4Ohe`{me1b^?vhT3qn^_FnmPV}te~->=4vmt93K zdM@Se;7f-Q6`YL!UzKlL>=9 zq}S$8<9+D6(ZTJd*;)OmNqwfwNL5|YxFu#5*!oy?Y1FPlwj%C0{En$UQq zWg8*_W$5nC&8gAo(0{S$(mce=Etw(L>Lr2hhZZ^-HJXHQ;=QKC5m9Wvi}j7We?>Sh z66RklocD3a9WIsAs*aAU^Qq1;l{sNLGp2axP%g$OfdK#K3Zs+Av-OV}idGcmEW@fo zYayl657tQ+ur@NEDddF(1xC@-&_BLo!IW-4vR|n00!{GU-h9IzbxI&imHoDHrpUoO zH3l7Vn62N#jE2*4GHwgc+>^TyKacK;EQZlaA944!;>vkrQTX3#l9J zuriSGN_rVv6JKfiQ>q9w8(H!)&WbbogUg2W0bcUEogA!ivH~p9LScmRsQO=~_W*7?F1(p`P$8k+1;qSJHC1Pl5SZ56XtV}o-53#gO zd7tY%(Enr2JT_xJMIrsD78?@S$QX=)j~@Ugz9;6)$ZHPN%}aXc!Tt>F96+dum`Y~%#2 z5i&ofU`e;cev#UaBL&?fT0I{7z-Ay`w}?F-xwu3pzDX2~l{JsP#3==>>fSs)8i5jR zp|!axJ=i#2;oHfmC}4fsR5D^ec_%LJF$&FpT!@264x2wGgducAFY+JN&_C@FKCEj^3yPud8DHcj8^VTS+-;(VcQ-S{!g5D;)f_1EN6@HJXBP5?c>2i^Ix>p;W!x9B zeuKHAf(GAl;=JLjv!TE0d{@Q?l&v^j`|j$AK#&>2gjw-K8~x_{;FrFVu!_vEZ&)m; z#$2f{9|Gp1p)Z9;wL3j|Ow=hyDGb&0UPr)YthwE^1WoSqxRM&El<6uOP)n(8ACO>d zG*m|WW9A=oDAGT~O3CDZm5wZkp`NNDQJauytm>4iY%;4N;l;eYWIsNb;>x<4Rd52> zUR1W`lX*GcV?{5cF|}7v2}_&LranQhkAZ23?9*@P{^p+RrXSlDi~UVn3 z^io*K$Lx?hno?;oMZ%p;FMi{ALjuHIAWT#xZ|fMd?Eu(z3-#2hG^*&lJQ&7UDF!Qe zPo4PmXV+Sv(#QT{O~z=*s0%H-A4uI)ncm!(v7}fvqqEKVldO(jUX{YjV#*V}Z#KWL z&7Jbw$k{Kt&RssBUnML&FQXlk6l@gJ8rv1fA3$g5yfS`njt&vSm}Fx}B&<%n)$mc# z2%oPofPS)Ln0i5E)PwXw2*>HMkCHMA45^s4{v4dxklk++>pWBrJ5??Q7s&O zD^K|iB0f&q@z(vGy%q2FNlmtrm*L^I|BLJsKXuTU^5J9mU^c>g8X!r(@0u+orHi6P zfn>R*hM${Nz2L{NC!cOlJ#O6|KHT(kjZj;+WMWuJw|XNL>28XHnKj3q_Sg4TK(|W z$c(XPT@$AUrWZn@ZPe8BJ6rH#T#go_Co51*mW>i;OZj#@OupfZ%EAOTE~z#3ounQ4 zB-OY%!XkBsgWnivM=rsm=h*S{jKR|KBfj_84RUG#5%Y__-pOkt9;e1iTZ?MYoG5oMm}TK{*i8qEE8JD?PkeESO-Ba5Y9++`OdEu+-Y)Uq$lxD)XCmUV% zEMVy3+aa3Rmf?prVEF}hY87T{*27P_2LWtME-W7?MoQ4={t%>l(aY|qabWzxeLM5q zO3W|4vFz6Ltp^UjxPMU}eN&b}I}_!CMZ10Q-tDLcQVy)kv@&DOh76}{q?fG2f+j=H z2m$5F8#OST*Y;uNW>f6_o9OIuwfS>OI}wDV#j-Iz?$OGO1?-xUC+B%pd8IrtfYk2g z@vmxf+M=;5GqL+K6>F~^s{A!Js<7CBlcXX%=q~~|@AfyGWy!MSbDP8>JNdAD`~j}b z)$rDIN0tQbD=r=l-vksmFEeU&CdlwhAxQ%kU@r~J99VzO!Sq|*hu?!I${ANsYDg6F zS!sAV_pbc8)fBU@%FR^OZqR0 z6Fp}p_W7`Tr@NgS`XRcK%oOf2sXCT=IVq8JXY^0PyZ)%Pc<68S^L|R9{L`lCJoJO* z5B;xE*b@k$g22{c&UjI-;UH18OpyD*12X*`X?ce!L2X@-g!-N($3bO2BPKl9W~Ep1 z;CCU5Uw9!!6pfNeZArva%FMZF2_und?onO^AM$A_tK+~P%MsI}i`t;0I=6a?Z8uO_ zu)ECkaAp(TzLJ$p*b!!>NWIHCV0t*{H(R9$D9C|!W%TJrpL zZzZMb)|Eb$k_kjdNnX{hr7j6b$txczc}e{vdChlHRQ$-wympJrHNJibc9bW3O(0%8 zd~L%o)w;%+mB*rEUp_W7ik&h-{H~JyzY=BTga0K_8dWo*HU%PHR15xF+!N7QEhc)wOiLm0DuVaOD+j{_T1SLS;!F$NQVAzkx&G84OqPS`a?_SCuVl${|9qP z^fxQA2IO_SWZk&T%;Nqpr&XYt#d{=b0{LeC8;(3y2GAggYv~d5HKYue(V_~AB8eT5 zp(@_M0f30M8af1jE%fSYt!nRGb!uz%t~#W3CRZKTx@*gDo#FpeSW>*61p`%B5}{dp zHR}H=`3GRTG3rYYa#V6;0YG|Gc>mTk0st6p0N3bIKsYTvqNN`1DvsfLFi?{3(jMEu zc4gvf00Y&aD5yFC7GelOfN*TULvi2O%6Wr(TpH!@K#~&Cdky|49Ucz=V7dVwx{CtW z-yuYR8n2jdq(j~S(>_3fP3teSBUw;k+{m)K0cL-Q1k)mV8cDGKQP39~DS$9T#0yZ}cO>8L8rSyi57K#A>3I+x`qa5>ExloS(s@#D8EU;EL)X0QwpetwYHZU;G2WjI(IJVKEoc|TS z|LctKLlm_^QJ_dUAv<5>jN>9xUd3;OW*dS)Ygf5qzuyi9%7mdpi)x3U9RGO`&-GvS z?Fb~03Gt_$1O*T+RS+)}llqlFG>uxwTgTUH*J4Bl(n&Z~7a& eA@vCCYDS6&Y8c2x3jjcnFCt<90H@*d?0*0dt%|8Ab5 z{MWuP{?{ha0PiCIXCY4KF%|;^2*?o(2uL(30SqIlzndw^7z7_MIvku%u|yGyXby|Z z>C!{$6O{}oF|aL)5a=f~%LcCmlVZB#znq$3nVo8C@)7X&|3b)*9;2A2O0QS^Ri8R2 zhkCIpX~Ys@cD2pi5VAqB?+9m$+ddTUdkmhtZWhin0vakxZwnn-(uo-_UuM&Sl9HV}O7i9GcFO{BbUsSv71oI*)*9}BsZdmb+6C08pvZrB3@LTtky zMW#i&M05jyQQ_e@Tf@o#~@-X<@Xoz}Q;5Kd( zKG@lUQVnj?3~1bAW=XmBbYM8v0}I9l1$*kNo-%8{q-+e3#1$m19T@_LQ89|A1s8>1 z(pgf=f4?Cq3Hm~pygQHo2|Uw|v&N*@>PU#_8WsjYz;yY&V@9={K8~1fU__N^g4`F#KS2chzd|i380`4JVbf#}UIg+lLWe?u z_!rS4l>Luy8Ho}6zfom>K{SK|2?XSX00czw->B-tLI-@9Y^bAuC$FYfmD`<{#+gbv zCAqs@l9lRBN_U~5jM?z*lSL&(H`mKXs7d6|n|U`wM{|S#+#<7=V^+^q5Mnp&E zcEIh{L+ygA`e9`hy?yR8m1}utR zvx8?3V7p&QX6>V1Q3U$v_OSGK_h?CaY4&ZDx~YtS7{%_~*uNnV8JlJ`JfEkjdPim* zB<^ykdTIB3UilB&QAZF9Uy1X&N%w1igC>neDg$!o=r$Hp@pV{Sft}@7)L2y1>10~K z@H%*T*qJi)G8s)R(rRT-nq)#c);1T-fE&hfC*;WW)E|{Q1rZ+S#ejWSLhaWg?HQ@e zB+%;}%-!E3Y|U%^tqsOiBhB2lm8WUNL+E)qG86oDX{!!N?$b+cp2>l)A_l;L3!;_C zngCx(nYHpvTH6MNr>j;3Oa)DDY@tb_b8q~ohhmCqY zXLNY+kf?4ywVoDc_j^RlNBNJ6Puu=nd%Okkoc34 zMiEZFa^|Ksgj1UNf~mNsd3dMZp?1@lVAHx*=_p0>Xm^xnGW$=k3k=OhBs51G+*+gc zCEwBJe&N)?a6W8{&G7q^?zb_U-vY=|u8ULnrAjVr^V9Wv3u;$M{3#D!UO~6MK8LxG z0m*lipIW07`bl?~pK5|>KE=X&^9S10WgFHJN_{gBMV>*(8sKF}pH-~miH^)+=`&dX{xO6RS;{G{+Vw=S2 zbvo|4ROHLPxIBY|;Lj^0rX|`BnO!3@!?2XM({v=ydsC-VRR8c!gfVd0_K_L6Ys7%M z6@l%U^Fi%yCrSW{16!_>8UCK4w^ILYSLbeTZ@bBw_&{GgC_Ox9|KC85fN~2jtgnzT zBf5Gvj<&aaC?4G2?xai#DS&-Zv@VA%O7?F=2vcvnMzx^%i#-xNv-Ycp)k~r-F6c4y($^M8KnvJC_tZGU>*C4)llP7 zq{M!-RXo^bjNWg$T~0q|{F2!&ch>`@Y)G{fbvwzw?}M>VzrMtlk!lDE z$^>T}8zJ`CRvw2~r60lGkqQ->nKH+7kw+5>D0$Lv@ppY3At@a6*TKMP)A83Y{6xTLlrnAn8G?pm~VBK z@II|X^viQXv>lN>4SuYyVV32_0Qelt!HrhPOj{GV)@$2xC#uGfps4X{M~~vr+G%fY zzVNy9d{u}BLMc4rR2Hm3?uN+wwcmIbNYAckZeM+AChA zB;pULLLyoJXA*@bD6RR68Oj5QFVw=51~OvXx_w3XurgzbL5KZQW1q@;EF6YSkr#8B zGkKNqnfCI;?KAF569$lh9Hw6O#%QB;v8B-)7J+L$?lDRUW4@PL#azjY92}h5LI>C} z43Xd?Kel0>1ArRd&Xj|ZA(MNcwd;Mr#TzGjS6@VngcWZbg0czaSz}%#zhDM)Z&R`X zSWmiGfV?Xbi%U8s9Vn|ozluFOsoNvzYk5>}OdpJIu|g6XYz-~CPkW?FQI7|*yj|(K zPn9IAXGF(Zv{KCIxJzjJOy}Lf_L_GvgRUECxTzC7A;9HGE|1usE~$D=0r8G0ozVCw zyK_+jIE+2)U3gYC!B&)4HY0$BkYe-=v^41)uc(u~a$Y5FJ&2rFglUiyY-A}?b|vh< zMeP)KEba#+$3&b$nMwGUE9Bq93(F1Jk1+NBg%70O2tRo{LYiQ1JK&@(-G+wUdTPb|1IENw+Y=-@KA;kEOyp z&q#oSCnE4uM$;?Ck~jJI?ZO*~GoMEdA@BHa?aV%f`ApoV$kAA^T+FyY=0h&hz z;CG9VZ*s|)$2uWxxgUy$AAcSKB#s*z++Mw=8TC`f#cIj3P zNGpyNFe}VD^>%hiAF)6^UCdo1e$Nk&zS-~6TRygSPF!NL#G7HM1HJcQ2U4TJ+A)GS8{5|=#cCo!07zfySr8V5W zD`!K<$KxEK?UAk{7ms*{BZjw4(xNSx8#9=vr<)rBLSENK2gA#`fq>jQ5m3@0N{KE+ ze8WmS-kO}h+{W6*ohDPQ(Zi1frRY88Bvv-iAN3eAXTZHN)JSZz6vm|(X4(Rl+6(v# zsQ`?aGkgnrJ9F_iZix5!3uj;PCIvUjByV4mQXN^`D15BxogfjL$F*@y8msKTFStxS zKF-Pt6k*N5?DS~dkxHk1$H4IqH*6@OJ#iIncUL1ly|!{;8QneRsutQ@mSm56s=mT) z2v(YC9~nv7m-Xh@_c^(b>t)eo3+sj1BY?&REKxXl?N0LxKk<3<&X)3YiA{p*bmmf( zRC8Q&V}+y(=AlcZk&*4Bw+mUhn{+hR$iN;m+2TW=%}Az{u0zz$Ehc|QARQXxLSut% z{t%gb>U;-xi(IDVfgO&ED$?)F=B+O6P>guW4m6fEEN+#mHM#6@Id4L2H zsSpQ?%FN{}Ut>r))YdCoIZ(kObc~P zVIzAA(6HOY9v|3_tD!Z)DK+fmA(>)3?U`|&Bg>m5x+($&-d0s_2U!Kf0LXM{I5_FC z=(Aw+GCIEwrqo165?wvzwhxP^aX>Qtd-S>brX`%8q|HAMcsq(@me0Zx&>VkKtu&cTbR&h$l!h|fe>BPQCo-2D z5g9_fk#jA{EzHH32sl;UdUUzyO(&4S95LN#PHWHqG4rlHRq$KIX|Or89{|+>G0K)G z5e+s^+WgGQjvo?e?yQ-VRHDRJDif?DMi&wz&3sf$|0jx({ddr~isH;XaC4=}h;kDp z&9HC9Fc;{A16Aauuf^+Qu-&xT*WN0Q1P_w%S0f1%xW!blZT(zJdq1a$DVc-5CJ$YY zlHPp^i7Pzx{W|Z&SA?qWEZ`X9NS8w1Ce1}b#OVWVH#tmp z4i(b6P$pmynE09CVnA2+5_b`AW5vVWof#gZ4&_YOZ|JPZv{faOe%^MvVV$J&MxnD$&b zW!abQvpIwljmq2OP{84_5s7cRhL^dCa2~fHby6;klr&jz6Z(ck# zuHuC1wcTVhhL95X0A1j$eB`60;wgM2MWDi2IiFViXOV#~uLO@^!Ok*;I%_XOcMDD- zLtR7jh&osO4GoLvDNpgWdE(_x?@#}T3?;+8m~(blsdMxJiG?suQ@{Dzd}X12t{{Yi zBsKje#icGIQVc(zysn7mx~+&wPX>g_T$5oeFdU7C2CHZWY$QN$?_Y~zDTgYjv{pdZ86Cl|E6Zm8e&0+)u2?AewK3eEqYftCg z=PnG)(293;KYNsmfj&t=4r>(}!>gmIaGcmmFx!_I8z^;ceU2$R9#mM9KAt9bl*@PV9 zDIovBbHhgjN%t8nS#zqle&QBbg%k+iDX(8}}Q=kLsQ3ratbfRm(@pg$gg!}JQ8P17^R*L6IBE7x&~0_dBo zoPJZmgr0hDMd?QK|x-{jzA*E$}4C(4SBMl67+xE&^fjmQG9qP zHdf@{WLKc=>bBHyd;6t@aZj%-R?Kw>>!pKP?wnhxUv@srm|%grE>2TM@n=!irhF;E zB2PwucGf+!gzL|45dycw4QPmSHo*5cKTt;%@fYNo(P;|=fN=1S#0mZoGhbkiCvJ({ zvzYQP8P?6sM#1g9*0l1_Gn6Iz`EyCLniurSC{OJ%{o*;08ZY=Nj)AB=dB!@u&P%U| z%YJtgBky_yK*45^>i*=tesWeEqUe@I_ktY z*rW*@=9R^yN!r1`85HVBpZ@V8H0XW5TF$<`zz>wzTQ@=aCg42cbeo6nL_gTD8dTZ^ zdS+Dy_ro*(FnYy!M}7yJSpobt@01jPd9n|j&l{H1-N;dE=Bcp+S`_U`toFX1LQQ{T zg2WPt{qa2NL^yB=l%YP}0U5nuOn8|fQIpW7!Nss#Ktg1kKMwyvw~qFt$r>fuo;Yp@ zuXD@Q9>pkcnZ&)HQPD|bJj^P4rnEY6S!|HZsb5N+sCj6H|7b1BDg)p@G(Rw385HX! zh^^x%T(vPMu7F&f-80VX=K}_GE$Tmr(?6N8zATWc6c&Q=*(GL)jQPXvT*9+XkXaZPKF-uG zKQRhVcpRfR-9slFd+`Tu$z;Eg*yhSk%lhv?YKrn8Zh+di5G(USqq_QkSRR`k?^sqp z(7y1Fb3McrcwYT!FP_^@n_@SrPHi3^up&YYLS$7C{wYJ`#sEi3zA2KQssx@15V=J! zQwu(jIy8_cR^^9Q_g;BVyjjyYDF|^AlKu~x@NefpdBsU`craGmH1|V{+)^!~{xnh# zZ*;|IhS%0kfd%+mxA7J`oy!_|g;`nnwk@?AFpl)`7G-UtA7pR5v$-#l`Gyyg^5HSR zposC%!HOd-%K_qetVAf8$lx`v+c031In75y-NJpceIN~!$hdhTww{jWsD8P%oFq3B znKqcZkM*SYn1+g!b8q&JiBRqBl10d-HC?*8_{oQC6yuZqyGW#nFtgw zv`N4gXfWOG;5hh@Xu|{;uJQa(r@DdwVEK;tmSulaIFRVT-_tbxWMF?5hp=maM(lnM z;X5ulah|bOn+^(Nyh9r1g&D>@)Q^Ba=KU69#xBpjF2%GYXyuE&Zx&?awt6vMj>SAH zanqzP|{DN}Qqh?_|*<^J$K;u;*wJj%5oL7Yxc6z`?cUXIdrXY%3^v z*<_VLR4VB9zWe<)LJ{(1*3j9S>ihj{M%5*0Ge82@_(YTq3=(cGW}9zNV&Ecbo6jf& zJpPG$x^l)rWX!ey1y7k_E~bl~zf;UurnDKyrwph`ImSp<1Jvff;|JQ@!*mMwrI?q` zY0R@Lowk)M{yw~!yD61&&rf5c-ss&2Q}YOtK?>`W?n~p}Oo`R+Q&Ee`b1z!RLm#_| z1m!jmp{Et5WZd7u&JoD3E7Q}o%uA#dgYN0^17mp`{ek#0Vj}L~yt09cSQBu5{$Yxz zkHD=4lX~-!9K9Td{QeU7znyZEG$Sndzl^jNYY5DLdFa@|Ay#wQh(yHODNNyrxfX^d8S1(Jnm%57oq7d329Gc$jPTTXDwggbN4d1{?=<$GS+0 z%`#*3?ZVv}nq}$aF2}yWHm^H(^ou(L^qb+X!#a=2Jw9j8I?S?ePr(pO#0jo|Z9v)n z*X!>{ICHhBy&xKb!R|mrYER9P5>L?)E8o?qxIZj}Px~e?{0snpVS9cW4#FhCIPW_t z=tpWs0*za%ib;Cs*JwxAoV#htyNB0tiw7r3hn9$r@8d;q{wu^+QjUZ51x#M_vL)0(^}qJkmdoPZ^v@iCaK zbZkCUF#pigVJG1FThYLQ;2$1}6}iP7Cb^|K7TVK$3JQ?{Rt$C2kelC%4DmFHN#veo z$lF#{LHvlf>$IV?h&lkCn1u^HTlzd99hoOYldOxZm{@A{Brc`HR79x) z0jQ==X2FYs@R{<|RS+$19AbwLpcyjX#|k(Mup5CCS16?;<0FOmQ*#GpYa$4FQiIUWNmFS^`=X& zH{FP?{u$S*k{}tGfM#u>V}IDscuYU9cM`RtBXOX2pTDnW4dJ!cmi`0Qu*?|+Jp@C5 zcSgvUQU8eQ6(DsG!$fd&<4b2MRT9%^I~r{|QCdEEMwskF& zG&yw&K=)dEM`f{^)H+tOW5$mW6OXP(&S|(eW%n&e#%#&n_#r>9Dr!ZN$Eu?nFG7&2 zHG(_9am8DR4=o`EiA3hq@U?km?-db?iV@0sFoCsWtubVZk@aBeRcn6=IUgE9X!fjH~zl@EPPUK)M*PLCePJ}nL zlap`d9o||5#4rqZY3eIuP|i~prCw8gV1A|yD4i-+USwZt0?HLpo*iJmYxf9W%R&KC zjNdwu&xD(Qyxr*avTZTSwOtRTKGQn<_*2vipoGK8BdHdGC6Z|ig;67KX$qB5E6WRe zW)gK-pM*W5i&52C?GHJqJLb@oY9dOMRcDc{%OlJR#SJauawXH%iHzq^oJIwS@D@}m zuyNQNhh-re0s9b|eV`JF=DbMeRT+ya;)VzBi=(k(N?fd7ImoT74Z5#nW7=|yQtsdR zIqq3W^4sW{64gkwXG=mXhDl(JWC6O;D#5NK!VGTqA!?{kg+i$Q4br>H#-^|$L`E8+ zg4Ux@5^Nfiz(M_qHiy+>$W3msM0AtuA+r*<4;uO82aB(@-2%shf z-SY63OwBM{^uKf}2kCT64e4H=hWnO*!2HRyyVG<|Cx5qSrm8v9I-Yl%1mTXX*R>+2 z6fwH3wf|wC%I2L&jdEm~d24OEB??u}$W+Yzq_*hP#9Q;6yIS(<*lT;*cGLA{RxwK9 zs_I490Ee9tRvhY$Y2X2RCrW3qikc6d+EK^%rHQSbW_%AVXbZ|~%q({3?!`vd9dilG zxm{-}=oI^&PKfT6i@$B^+Ta)D-bF?A-!L{Fr#zx!=u560`|jx(ds!T7%0^;j{>e@r z9ajvMTkMg>tM`g6BKCjxCI-(aYklmWwvU^x0aKy0b4}CWjqQMIqx|7RvEo!@&+83M ztIyShD#{GESOwY#mo+eW8^yF0R(h+cVOOsK$=t>5C@ZLCPj?szo;O~nS_u%$}%)8J8c4z|0d=0a?jxHLmgjs3}tBl0t+Ms+C0ir;vR zbwPISq0ZgZYE(#_+dvWJAd?ElXKNEA;L2D6&7(STLiVKIPYV9-$zqT+BmS<;& zJ)4j`kDXQX8TiKiZnNhU7>jwj=nPvooPHJ95c(5qfC>y@wMlvg5o7A;M;+?TefJfu z7VHiEGqr76nAb2#*0H)C6W0k|Vw$+0Sa;HaJU6l|Au>!X*pO!BI%_CV@dIxH@a%L8 zH&f(mjDem*&_@Ysws}Jhz}k*rHaI#B9xIDAS4;_D=Z~{iroWkgwb6@nKigH5RcqQwA5WeJ50l%c`KFQRWI<2KJn>gtI@Td_-;ax4lkE3Idw4Dg1}Vu)0{v>;&DA z-I`=YVU~7IUs>dSNgI)VrLE0xq%&SokJQ?249+0-Z<`mpd%Kx@6N~}lc0O>&CofKZ zuO>&21w-ZQ0BzfGLmLQ8fSIEcMA~H!;ZlK@F85#ls7d*xv7_EAY}f4oh>p{Xd){b# zR5QCGmv&M@bn%7pL$Rqy;Zl??P0f$0H6$eP z$DniTgec|b{qj-YHm4@u!Spm|Zm`Ur+$`#C95zhKTaV71f=|uz0nZ`p)Z@Tx3ki!R?x_x8z_TFxR)TsCHo$gTl@Bz$sRk;BqyqEM%3pRnu&FQrI7R zqiW=h%%$vUiNW%2$Uh_J-D>rOUCou?Z}_HQ!)?cMQ)+TyPZ(;h`yzZ`^4^G+p*~k( zUBV*ISyIAQA>`Vq2;BUCy3DnYXD1E>5YS(^q*ySVL}@GlF;jFTm3B2%O>-#Ka7#@f z6^ORAC^&datD9u5k!yNH5_I^MN7w3l&#GUGyBIC8Z&r*pbQ z-0L0HOI!os5Q+nb!*5d*^i+5XaXhK02}z=lkXwfkc9#=Q9Wi+zcmx7EHrHtKd3O~=>KgXZU ztSkiETOP9FUS(Qa-kXcr$#UiN3-G0vs4Y_f%Zb*KvtS)+W!d7@)-CmkSm_lnHryQu z_9C>_ETtjob93J`*Y}!qM80JxC!8#B47tY3 z(m}R^4dqVcq}E7{+seq5TW+(80q)v;xY?CGcyx#T>d3ZsuPn2hT|Hn25#c6$^qW0E zHR4UxD-hv)Xoo7YJ$z8itE2pg#H;2AQh?nol5IFkI z1A+jNFlCh-&b$#)C1zx?86xUt+-rnz^A2wbB}#RX>N5X;dK1k?L&Q%w{lFy6$z@v zX`SmH?4O=KR>mT3w0V={?r*mWZhQ#&`EjZP`Y8L^W>CO#(Xi z=|f=T7G}P+)JgSF2K;4ZzO(ym8D5?D#MA`mLxSnEvVP0I<+Af5?U}Wsf9wnZUSgZ+ z(P~!F7ZS%u?LM4me}GBMOQ=v&P-UKxf<*+CaV_b>m7lR@(MsOL45?_LbFo!%Q$`B6 zSdPtlmvfhs*{(F-ZjMrzRCj#EzP0QPMTy-DWIepVxm% z_3Ay}+4v|8gncg7EPh{K8|vKwP6~`WlLxoz$a#*W0u`rZ(~3G`t(JEXrm6XBPex*X zKIo4vD^-g4BD(ilt?tG>7!&2WhDjFZPGrIf&Qla8Cf}YR%N_naKmIcu;f-?&IxX^Z zQJ-7QF;@;xeyiNa+3XBQ(rgV!UhvN3DXcbul{|;;$(Yy*_M)UCZ6kOJcu}b`AC0;L z!Wqbeave)VCr-U2>sCgAH;_0Rm@`W*-s?j68K6x+ngOv&Rx4jDX8M5fBTiUM8r?)z zt&=VC1%s6$(mbU(jwv!;)YI}u;6LI;n>{8c<>V&){)GOVd1u9V)E72eE;lBw_@gXk zf~-~S1bM>|OOv`}Fk*}dIM>VP@o|wIZ75DsT>{BUra7WXg^4yKjZ208jGdR;rha7$ zHaH^RX9&53P}_FeT=MzO!&RZXanDF@Z$+Qnswi`$&T6N#E(;EQ-4Q8RD>j`=aoUvG z)A_4Y5^bJ11$`kz-U1J$3~gIX60W$9sFD~P|IAu)2Ul_fVpVGdK($u{aVW$F7)3!D zR%!mmXn@)f<wB$Q_oR!AB}2&kXqa&ph4#8mGG~Rp)3* z`lYA{SZeRFyr7rz3*VSjKg&`^Dp7=@q2hlv*}k@f7*GN*VNB#->E5yRgQTcBs9Wja{-ZrfNM`>1g+cVI;h*wp zU+j|H-b6w^8z&ld1WW}@(yYx5@(iT01l!E~uq3Oi#A?A+D$BJ*YNg$-bG3qAS0s`D zYZvj0@e9^&hX+c^kdI-%!{vtSh3=vEB)8+|eRc~GD0+{O`<<8sYq$_E)fHh9=boEk zw=gmgfPgNBk70{X-c1H6aqZ;hNmbQeyx$nhuKO2xL=8W0=%nNw7N@uTK&G7{jPc?h zk_IR6hhq!3;G)jzwKF#D4j#X5Hw#Dna9_uHr%L(0GStDwQ*OwE)mLNah4r5f{({Co z{~*j$WF(8mzj%KPCcj@&E7g$#rt|_vL&)GAPtKF;OU1TAAjoxF!{e z&_Zj;B2yChnA}!l)kK9hT*{E1HuX2qiaw^4kJ5o2zo_15quWuJA1ydSgtJYi8&D!6$l176T?DYrJIe;{MDLh!Z?0OaoOl9J(yRd(RE3E zT6^SDdYLjoP=INkupKlU{&u~NlEP*jQ7xOw1LAe=v3#kbUgQ;hXgUeLfa;P3(4sk& ze&nb^&jDMq7EQxF4oOK$S?_EpujD?j^p;w?7DpGiZBz0b9A{Y2T4&(VA}%lwaZv9M ze>5SAZ~~QZT_uk6B}WK>kesC z`<(BuyR`xRhoFJa9+g7xW4T2D)Hbnl?BTt1pmm6AOG=nLu~wS?-kID(r1`eo)%zUp z*UBaZyXOn_15y24>o;(m>Nju_8Ic3M*>ix<@26KE4v*Y`pwU!w8tdP2TIt78hp(2= z^d%5yP}5?ntfE=B!<{tND_p-0KWZv;X%(}5?|#H{lt66ni2%K3`swQf7)_8W)+MmO zVrn|jY;)WK^B3=dS`vB6HCJ?c-vn{usmy7`>F^}$G_LJtIMPAaO+2fCLuRoymAY-G zc`6#L3mkhSUaxy?EVsC6cv6lOYBAiBJ+ZnL(|`C9ikqa=-owe2;cFoHeSV=RC!-%KF*Wv~!R$=-NDGx@ z8qL<~_+W)q*rKdmmxp}L#mts8M*wYK3GiMsDxG@0h87aPutNvHU-w9gA-=z4n;jKb zkd<0~`^ek6?_MQX!bn|ST;9N29!45W_oF(ezKC5WeCU^V zV*BCzcq`iO;xwy1Uwtpd*LyI}BO)*PBO>UJ2s$zEYP1Jc+!)Dez|T^O?)#b*XH4yrD(HJsd+3@RpR+M81q-7xGUFs2+h3t>OY12D#qGbOPN= z^Pe1SnY_rLZF9`%7bbrEgg(g!uC@YWroY?;`Gp&T?vZ2h6A{@`EmyWB0Hq=70j?CB z=`+Fm1+El$h-EC+x^foH1+Jxhyi)-!@x4I-xNPkopTAk)cx9mGPYvh0(x3TDedDDN zKXwB(wFMf^VZ&~zzYno(j(Qb7EUJU_`G>S%uT(f^wc_^NW{8M9wX)3BU!GL;|@#Y{~-R~6nlqQ;+~YCEs9Sqr*=y-t@P`c>aY4{W~Me~ zb`3{&cm$h*M4*5?T9lb%1G? ztax<7As_<0IE)HXQJI5(j{AgzH<1A8w3{vxYM20M$xXtF{dH&H_Zj=!k4?RJ-qc zapsf{qQ_-MvY|6to{lz#GU%QSbK{{iy6>C3dg3uwcxn}`QL8VcBTcpv4YPd=Rn`#`!y6x7=lkanb29vLn@5#rg zQl~$S*Cqt4IMtdw=k>LiXhx{3jB}HaVGkZRTh7zfn)baVmX>#$N@Y?$bQC~9q$Q5g zSC}ZWmF+^VPc1!?){@oGb0J#s><(zy&DH2UbO(B6lLoO@TmjJ`japdzbwtkd44EWa zg&7q!bm=oJ`#FKb$vu|Iv$(P3&)-I25=Bkc0=E~E>|x4!(N zu1a^k{`7r44F`Zk7XtK}cO8qCyawAr7Y0QUnqpVI=c*}`!(7{3TTiRSTeEN~HBE@A zB&)YnmeH3<(;pR<+ah)MBj9f|*c(UTxRq*`ryGaht`b{nXP zg}fs`HvlZ$x%rBWaJc!xYPfaBIM7P&(3@e{SOlNGBJ@`6`+VBlmgtSVxP1Z%s5;IO z`V^fFSTk(B4>_X!c_J_HB z!r{{R*B%6M)*WEJl8?D8^qhoHVIO%zl-1H@@&k^)2udI44Be>o8n#^jcFPuzAS&!{zJ?nLQvwd zy(=kZuMOEOL8fQfogag|uz>RCqols-DBo=M*aV3yA z@eANUnPmWL;ax#wHEQ9CwT{w z>gzH8{_yBhj%sZKYI;ZXm74^u2+d@rKp7CNa@me>^@rY-CVgfruy&VbMtQYlx9&8v zBgX#xk{|}JCm>fxk_s!Pw6IrSTT-VK#=R&qsrVYvu%s z`%RWOu;)`NSCsJCD1P?kfIxO%Uz77U=3E@66A~kFj6^w~6c`4eFRt)6mN`=}6E9!_ z07Mbto1KdMjqce%iA5S#cDNDWAC1ZhEqTV2O(Ic7eWBZvG=^I(r@ZgFo0RPoBbDQ7 z?C_`{ITO}2T)aKpyY?22#76uL{IQeJ3X)PLK-Bc~S@yL`%v9E`y}P4pqMO$ngEoGd z6&vjn948K@mpBm?e5iuWcgxN$M$vc#?kcMxKl*7?cUQzn-3`xQ~M_i7EcLLx#YGy1o zo1Y+x7^R!f1MbqkoAi#Mk#PPiXKQ7#%kOD>izUfymY_4z@^F1L2M|)n)-H`wb6U%P z>>l0@p;;utjuc@1DAA!@NTyw`WgzClZjJaY%5o6kE-#yC#4kULZw%`zCut?joq#e7n5uS6ksx)GLDc4W>@{c`Jex0ZLg5I z|4GMkVU-}r|M5{l>#3=t00C9d{O87GgAXZy!Nk_c#U)1z+E;a{f-Rz6L-Hy+d&BX=97vN+&V@j5R;(092XD0h0=f?Nq$M@uLIxde#Uex7vn&=9U z|C2VGcl3by_Ni9X2Yz<**dWi(U9f;ak&~IuHnSj=wp^4HAoSd*Q2K>qg9CZb^`}$5 zh|8c1gq@Y3Km|E&>O@I5ezvGXk-yB6SG)|jovPo&EwlfCm7s3H6am~b@RMJSA2q}{ zQC{Qj5J({*!T2qkf>Z^R7hd`P5oi`L_v)HMlWumBfs=NsI)b;WY&ChP!az%Ns6q{A z4!uM3Hif~p)XDY6n>HJ-5HMta(7rokOaw zS-IfF+!UN<<(n#x2{ok6Puf2@LgU8l;{Mxxf`RtXC3fcI-fLc`;_mIOIhPRtbxRX- zQL;g#Q;Tqmli*|bn=yGO2B&V}jM>N+8B@}sr@c_u`v}JY>UN}1BT2r-H{y{U!ZS(J zqG=}W9wUd*gr#3c4CS>*>ja|}WRoVz4yTO;IjMmer)A#_nI)kfMb<>agJP(`(uA2H zwsmQQn|r!FBYK1lfkm!@1$7xPVL2E{F*trJPn#BA(XXG=VUN4;8dbPa)S##2;~ayn zpm{f1oYBm>9gEM%Ij$RQ)ja74siNe^nb5!dY-`soCnuD)zFdsnCV`40kuh4H;4*k8 z+Sp)2dwBki9P=AZwQi52MLHS>Y`a&M08n--`f9O;6#Y*{rxzsdgSJd_^3 z<%zbnxM8-47SUX+B24& zG-0*&{nox}gb5SX00bVe=$YF0OJ&vAZM4Q*< zqG$a1*Kqnfbmv-b!j;UtGZ)FYKX^xwY_Gi5AZwrLfgx?`v3&{PwawHP3gK-URG^^& z7B~Mea%)$av-=8;y#9c(lqIZr^igOHl);~NJuo_;OM|4@_#dHq zvMZd?s%}lxrJnux@`@=$MBkH}nU0hsh5ygH*x8;f8?r}EM`TC)lAMTl2bng~+|`A_*4O!+Yc3H112{&A4rT3h*^<0rH~KPRWN3)7N9ET^VelFR zWhgVB%Enp*R9h2Fgu`$nlD90~w(*FHlxbX~=I=K3qsT>oq)@14)gW}jV$;?+gzY6O zsov_Mg;h~*b5egWIx6D+F~o!E8OAjYFr!4P&5xYg;@yF1 z31gw1oGB6kHQSx=vS2TZrX*L9n|!;G!6^);pE_OIIwO<^kao?w(|_D+l=)5bZb0EM z(;|!~H`x-$jcA@KSh#Z{JO5uBR{{>@_x;CM6Invc*oH`1vsYv*yR4aHYqE=?kiyI` zq3ju3_AN^ZF-nXrJIUBpc8w*8nC$d>8-CyZe&7E)&-*-g&V0`2oO|9ocjme0-t%e1 zO^CH`wky3$HpkwXS>!TB%v-;;`VQ){m59kAZZll&H8D1h&5zONbmM{>ofHcy>BMMi zthMJNUl;qzxGFaMM7_pb`@l*=Gpci+%M1NOYVN4lOEufv3rWJcz9m0&eSCxvrk&qQ z-x3rNg!OYS1lW)Fp}aBOqo5`V>Ta3ii$<)cYQrNSOR~NvmgMJP5911b3$Qnso$O0n zMrmw6!XGpHeJxKceAsrpyCOG!AfsnP7gI770I_vnmcx%vbfZ=((3K;l(i`{udDJt@ zdM6e(Y4SQ?3SDBA4kg{wR0TyNzVoqNM4IuoAuj*p<8I61JJgsv#4l(Ep-$H4$C_g; z9B9Tr+OlO|V7OR+A6znk*Y6bLVM7rw*u|$f#lr+;Vq~v67e8*b^TaH%X0@Qo@;vpOv4)^MhLq1*Fb|F>X=s_DxBz~}<8P$L5yu*m8YnQyW6K3Cp z%!_RNdW}0=vno8rt|yl(N}cf0M~2>eYI0_3#>cma3znej-(mCOlk~m8Q#3`3{*ktF z8*(i6H{0_Z{N%lDjG+|cHPF7A4)K&uT}EWuINBH$8X+`t^dltJxh)YBtN|Pm6MXM6 zHM;vG(B(&dojN0JnBj`j**m@-=jSSJR&J(lJ2sg8borsv*s%S5J!%EpSDkA!^Pn$H z`#KM1jQKm(w@3AI#y!n1@J()Cb)8v-<6sjLq8qo>cKk63qLw{^jk6$|H?<`(F1<*J zAuU%C#r~}2-T1e&L z)6Amf3m9vRf7$8l6j}ya6A(Uk;-L?fo>iUYh_8$*PHclVMM=oSw!yUD9iL)dgxm5E7;W)O1wd{z{gIV?#wMP zZ0TKJWrg=>y|K`VQ=pt$@Nr>#P4#AnMf7um8yrDT`L#8h@wIbDAa$7Z^A`H2-F?DB z!}F-yuV*=ixo%{+Dli?pO=W7SG&t}MCbrGtsE$#(r9INceSS5Ku1hVUKdWG7XShh7 zb(3mCt!mClWLHt@ylCs9R>IRybk0zcn`jTPqGm%nPkeSWFx()-Md-KBOUq|YU+e8_ zP7nUnQGG8-@#|)`Gk6$Tvl}&~HFS(`TgZL_#m+B76@vctVJP;=?Pto&ZncBjaIi_F zXSwi|4~UlHRhrUe)AnSZ{^B{h#Dy0T`omfA#zd#xMgGWJp57XKH_SqNOIbEtFQ>c` zgMR8zj5-0%!(DsgG2*IYTS-MxC6y&7Xf?pNb3As8D9PsqSomP=pc!5%_2)>(m>I|o3qWTUm^>wSRpS!F`ahT*oPVt3P zwtXxs>#>7+f%)thzvY1*R`HytUL2$0=?H9JfS1bCo4?SFuE(z(S!^n^p$|$M>(|@V zYR44!n2qTPMzJz2i&M$<-1R>ZWXY4J>x2^BvvcP?hMFJMVY(R_Kw=Kyy7z|gAneRF zb7X|(8lfP+*KJo9KfqNKq+Y%(_l%#E)rdwuPwtUShD}waiqO1)4UIkC$n^u}sU)3{`fcO_*RFY29r zCR2HnMVs#V%`v#-4^XKG@}6JiXAc3N_J+}q@;9zR{0ADcGn0z8)UJbGE$fkzEpnX7 z`*{)`CKK@?yJ{Exr-+R>hO(~?VGAGl^0+kGg)UXy{j?L($k$!`J&T&1)sPp(Zm3lN z9*>meom7sLHx;+mo$ceeu9f)o3F?cBsJE$%wT`%#pha7$`6Uaevfd(zHF*94E)q%q zV*Ru_pD}G(rbu)qXLQb$^h*~ilcub6bH1A z$xs*Fd(mpXWD@S8Ql~NWGt^5N^*ieJlnOz72VNDglJ{lxI>J_>f8Plf6F1K1BJbh1+??YJ=ye=5%_`1;(N1MT25oUnVo&7|-kzeLghrLU4&` zuz{i->q0Bio0hI4qtey7wTL?sVxDFu%H1g)8YJEj|4P~AJ2956G0*!pP>KCo-3>Fl zrym=ebvrq{jP#JqM5WqzsXFm$o}8|bmV9#>3Iapl{s>~GmGRKin;xXN&+!0rZG@6z zy{dFL)E?FD*kGewe1wYrHmUdh)=Egn^ni_FMM)d{YXI|Ui?1n`(o_gw z+BS2YO37SKvp!?Id=jBj7e%X=K=M)q-3e;Z%WKXO9ri(&=#GZH5J> zrOaIoPNTTAcWW7G^VxK*4chVePVZZ{a9?u_A0cl1N4^7i&xzvVEfmGe&J=Wzca4{i zh6BWQ+nHLw$8fgZYj)6AG+xdXjfheni%qv8W`o2j!TNRPK5YDwsDbBN82h$u{=lnBQS#(5-6ky_ee;<{xA@(CTbm!88felYroJ zWoqneu4Mr~K1A15Q&D=!wOUmJ1NuzkZ}MvdO%YtF!1He50uw627c1YwS8$5EC`+{z|bC05?(W&?ThS-+GP|td0^o|(n-?TVu|H% z>h6t(1%}S7jK-{)uc()wm^*c*>!i!aOSd{V`*5i$lm(ytcDe23qZN9U#_UxRr>!7r^7B=P0GwR8R2J726vAXW#p`hpyW(n!f>|44NI;n> zh8VhBBnOfxKk0s%S6jd@s;M|<9uA5|(GvVYnVW`YLBE4L7Kd;_7tO}5(Yu^6y1gs9 z3-vmhwS>MH)nSX^DIB9MeO2FlcZ+Gcjq?8FJuTrm(JkAYimW{i^mmr6NXoLs(g^1O zJic}cwP9jd@wV;4yxQlh#$VGcr%l_w-E)0vq*5Wz{^s0~iCapVi#2ST!Gb!q;&OG$ z_xI>7H%ap-vnhWiG~IPs^P?CZTJMV$KCSFmSYE3hXef*{EY{C2gSQi3X~XKb*(qD~ zG}1=Q^&v_|!I0I)2l=FXwn( z62hFC-jB83{r3G^#JwJ^-+~OUH&FBUCBl{8U9Q@m8n6D5s(?@X9lbYEmK6G0=KHT! z((?k;^)6-u#b6(j5%;wp%KA3lGG^vUikj_CA}hETFq*JOu3y{yNqf0ITXYuUoae%- zJgkp5eAK9h!r$D+CFWR1t3_O9!7yzOp)4x)0m|F4RA|ImRzxWK*tf|d6PC~EZg8^$&8{YFuZ^?rk~_CVrXd;R~ZsMc3|5?jZ4 zT*o-<>vZJH*`cImG5XBz>fy57iL&X5_g?&$$>mlHT zvt;Ef$7r$I^$@c1p_6rol=+m%;KX`CGVt$4X%I-@5b%j68MssrB?HO3;(+w6IVA|B zcnCPHPX?+qoFxPQ?!E$nV26O;uaJTDcslG26PkZT=TA=A7*H?-Zoxx}_U71efc?)X zJe*1Xi^2u2nFD!cVe){-UVjf!*?{klC#Smzdp8G3J2#g@L+cM&OdBad2^d?Z)F9B= zzg)mrICTwcYbA5Y#XkztwhqyG0B{btMGh&HUB?=>3St>;X|YO;4EtW_H$uSamSlN& z<0-yB1o$EY>8F523}8|D5J4uE1=w6+)Ix*ZZWP$phc!XK5ePt^8$01}0_)Lqz>5at z0(NBHx+al*>;fRWbc-ze!y(noy)QRvhJYP!ljYIPXZB?^fGpRO%)8;ufc0oU;ALrn zfFIsJ;1DE-`)_&~Soc2U@BIhZk^m8Gb<2TrC!kD3V`p2m$%@i$@He_ZN2!30Y93O2 z7X(-^BZCgDsviP51p^=fEU}e!-{tLA2>5p*Ho8*;tJ21`FSBZcfLD_b+@-;0wQ(MF z50DS00nd*Mo11;|U(XPmhG)kEp78^oi5)T;oegwJ0DCAV=ynJ={`o&fn%fVa%>p2Q zTmZ Date: Fri, 30 Oct 2015 22:06:36 +0100 Subject: [PATCH 090/109] Fix for blockcolours not loading properly with the new forge versions. some toying around with the gradlebuild file --- build.gradle | 12 ++++++--- build.properties | 4 +-- src/main/java/mapwriter/config/Config.java | 2 ++ .../java/mapwriter/forge/EventHandler.java | 26 ++++++++++++++++++- 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index f1a853d3..3d52902f 100644 --- a/build.gradle +++ b/build.gradle @@ -7,20 +7,26 @@ buildscript { name = "forge" url = "http://files.minecraftforge.net/maven" } + maven { + url = 'https://oss.sonatype.org/content/groups/public' + } } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.0-SNAPSHOT' + //classpath 'net.minecraftforge.gradle:ForgeGradle:2.0-SNAPSHOT' + //classpath 'com.matthewprenger:CurseGradle:1.0.3-SNAPSHOT' } } -apply plugin: 'net.minecraftforge.gradle.forge' */ // for people who want stable plugins { - id "net.minecraftforge.gradle.forge" version "2.0.1" + id "net.minecraftforge.gradle.forge" version "2.0.2" id 'com.matthewprenger.cursegradle' version '1.0.1' } +//apply plugin: 'net.minecraftforge.gradle.forge' +//apply plugin: 'com.matthewprenger.cursegradle' + repositories { mavenLocal() } diff --git a/build.properties b/build.properties index 22e7fbf5..73e76f19 100644 --- a/build.properties +++ b/build.properties @@ -2,7 +2,7 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 forge_version=11.14.3.1521 -mcp_version=snapshot_20150615 -mod_version=2.2.10 +mcp_version=snapshot_20151028 +mod_version=2.2.11 curse_project_id=231387 release_type=release \ No newline at end of file diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index 17e242da..fe28fb1a 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -70,4 +70,6 @@ public class Config public static largeMapModeConfig largeMap = new largeMapModeConfig(Reference.catLargeMapConfig); public static smallMapModeConfig smallMap = new smallMapModeConfig(Reference.catSmallMapConfig); public static MapModeConfig fullScreenMap = new MapModeConfig(Reference.catFullMapConfig); + + public static boolean reloadColours = Boolean.parseBoolean(System.getProperty("fml.skipFirstTextureLoad", "true")); } diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java index b7fac390..8349271a 100644 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -1,11 +1,15 @@ package mapwriter.forge; import mapwriter.Mw; +import mapwriter.config.Config; import mapwriter.overlay.OverlaySlime; +import mapwriter.util.Logging; +import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.TextureStitchEvent; @@ -105,7 +109,14 @@ public void renderMap(RenderGameOverlayEvent.Post event) @SubscribeEvent public void onTextureStitchEventPost(TextureStitchEvent.Post event) { - this.mw.reloadBlockColours(); + if (Config.reloadColours) + { + Logging.logInfo("Skipping the first generation of blockcolours, models are not loaded yet", (Object[])null); + } + else + { + this.mw.reloadBlockColours(); + } } @SubscribeEvent @@ -116,4 +127,17 @@ public void renderWorldLastEvent(RenderWorldLastEvent event) Mw.getInstance().markerManager.drawMarkersWorld(event.partialTicks); } } + + + //a bit odd way to reload the blockcolours. if the models are not loaded yet then the uv values and icons will be wrong. + //this only happens if fml.skipFirstTextureLoad is enabled. + @SubscribeEvent + public void onGuiOpenEvent(GuiOpenEvent event) + { + if (event.gui instanceof GuiMainMenu && Config.reloadColours) + { + this.mw.reloadBlockColours(); + Config.reloadColours = false; + } + } } From a0cb45ed6acfe0adcc7d6eb73be9abfa950063e0 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 23 Nov 2015 23:23:35 +0100 Subject: [PATCH 091/109] update cursegradle version suport for forge buildin version check --- build.gradle | 4 +++- src/main/java/mapwriter/forge/MwForge.java | 7 ++++++- src/main/java/mapwriter/util/Reference.java | 1 + src/main/resources/mcmod.info | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 3d52902f..4bfeb382 100644 --- a/build.gradle +++ b/build.gradle @@ -21,7 +21,7 @@ buildscript { // for people who want stable plugins { id "net.minecraftforge.gradle.forge" version "2.0.2" - id 'com.matthewprenger.cursegradle' version '1.0.1' + id 'com.matthewprenger.cursegradle' version '1.0.3' } //apply plugin: 'net.minecraftforge.gradle.forge' @@ -129,5 +129,7 @@ curseforge { id = config.curse_project_id changelog = "" // A file can also be set using: changelog = file('changelog.txt') releaseType = config.release_type + mainArtifact jar + addGameVersion config.mc_version } } diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index f194416c..cb2bd233 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -17,7 +17,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS, clientSideOnly = true) +@Mod(modid = Reference.MOD_ID, +name = Reference.MOD_NAME, +version = Reference.VERSION, +guiFactory = Reference.MOD_GUIFACTORY_CLASS, +clientSideOnly = true, +updateJSON = Reference.ForgeVersionURL) public class MwForge { diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index e3ebb219..663ffbb6 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -17,6 +17,7 @@ public final class Reference public static final String SERVER_PROXY_CLASS = "mapwriter.forge.CommonProxy"; public static final String VersionURL = "https://raw.githubusercontent.com/Vectron/Versions/master/MwVersion.json"; + public static final String ForgeVersionURL = "https://raw.githubusercontent.com/Vectron/Versions/master/ForgeMwVersion.json"; public static final String catOptions = "options"; public static final String catLargeMapConfig = "largemap"; diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 7ff06307..43d81416 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -5,7 +5,7 @@ "description": "An open source mini map mod", "version": "${version}", "mcversion": "${mcversion}", - "url": "http://www.minecraftforum.net/topic/1570989-/", + "url": "http://www.minecraftforum.net/topic/2523556/", "updateUrl": "http://www.curse.com/mc-mods/Minecraft/231387-mapwriter-2", "authorList": ["mapwriter"], "credits": "chrixian, ProfMobius, taelnia, jk-5, Vectron", From fda80350c20a776d27161bc78444ae64be4c3be8 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 24 Nov 2015 01:25:01 +0100 Subject: [PATCH 092/109] save marker on adding, editing and deleting. fixed bug that marker groupnames didnt always get special chars removed --- src/main/java/mapwriter/map/Marker.java | 4 +-- .../java/mapwriter/map/MarkerManager.java | 30 ++++++++++--------- src/main/java/mapwriter/util/Reference.java | 1 + src/main/java/mapwriter/util/Utils.java | 5 ++++ 4 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index 7a03a64a..6b409cfa 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -22,13 +22,13 @@ public class Marker public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - this.name = name; + this.name = Utils.mungeStringForConfig(name); this.x = x; this.y = y; this.z = z; this.dimension = dimension; this.colour = colour; - this.groupName = groupName; + this.groupName = Utils.mungeStringForConfig(groupName); } public String getString() diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index 39c24273..60fb5973 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -6,8 +6,10 @@ import java.util.List; import mapwriter.config.Config; +import mapwriter.config.WorldConfig; import mapwriter.map.mapmode.MapMode; import mapwriter.util.Logging; +import mapwriter.util.Reference; import mapwriter.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; @@ -69,6 +71,7 @@ public void load(Configuration config, String category) public void save(Configuration config, String category) { + config.removeCategory(config.getCategory(category)); config.get(category, "markerCount", 0).set(this.markerList.size()); config.get(category, "visibleGroup", "").set(this.visibleGroupName); @@ -80,13 +83,18 @@ public void save(Configuration config, String category) config.get(category, key, "").set(value); i++; } + + if (config.hasChanged()) + { + config.save(); + } } public void setVisibleGroupName(String groupName) { if (groupName != null) { - this.visibleGroupName = Utils.mungeString(groupName); + this.visibleGroupName = Utils.mungeStringForConfig(groupName); } else { @@ -150,12 +158,11 @@ public Marker stringToMarker(String s) public void addMarker(Marker marker) { this.markerList.add(marker); + this.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); } - + public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - name = name.replace(":", ""); - groupName = groupName.replace(":", ""); this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); } @@ -167,7 +174,11 @@ public boolean delMarker(Marker markerToDelete) { this.selectedMarker = null; } - return this.markerList.remove(markerToDelete); + boolean result = this.markerList.remove(markerToDelete); + + this.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); + + return result; } // deletes the first marker with matching name and group. @@ -188,15 +199,6 @@ public boolean delMarker(String name, String group) return this.delMarker(markerToDelete); } - /* - * public boolean delGroup(String groupName) { boolean error = - * !this.groupList.remove(groupName); Iterator it = - * this.markerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry - * entry = (Map.Entry) it.next(); Marker marker = (Marker) entry.getValue(); - * if (marker.groupName.equals(groupName)) { it.remove(); } } if (groupName - * == this.visibleGroupName) { this.nextGroup(); } return error; } - */ - public void update() { this.visibleMarkerList.clear(); diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 663ffbb6..038a3d42 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -27,6 +27,7 @@ public final class Reference public static final String PlayerTrailName = "player"; public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + public static final Pattern patternInvalidChars2 = Pattern.compile("[^a-zA-Z0-9_ -]"); public static final String catWorld = "world"; public static final String catMarkers = "markers"; diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 581bc1f1..7f00d69f 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -45,6 +45,11 @@ public static String mungeString(String s) s = s.replace('\\', '_'); return Reference.patternInvalidChars.matcher(s).replaceAll(""); } + + public static String mungeStringForConfig(String s) + { + return Reference.patternInvalidChars2.matcher(s).replaceAll(""); + } public static File getFreeFilename(File dir, String baseName, String ext) { From 99a28911576afd9c61e222ded94192142649e3b5 Mon Sep 17 00:00:00 2001 From: Vectron Date: Wed, 2 Dec 2015 00:27:52 +0100 Subject: [PATCH 093/109] dont save tileentities to local files. update forge version to recomended update version to reflect changes --- build.properties | 6 +++--- src/main/java/mapwriter/region/MwChunk.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.properties b/build.properties index 73e76f19..a5b65216 100644 --- a/build.properties +++ b/build.properties @@ -1,8 +1,8 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8 -forge_version=11.14.3.1521 -mcp_version=snapshot_20151028 -mod_version=2.2.11 +forge_version=11.14.4.1563 +mcp_version=snapshot_20151123 +mod_version=2.2.12 curse_project_id=231387 release_type=release \ No newline at end of file diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java index 437f35fb..bf069a12 100644 --- a/src/main/java/mapwriter/region/MwChunk.java +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -450,7 +450,7 @@ private NBTTagCompound writeChunkToNBT() nbttagcompound2 = new NBTTagCompound(); try { - tileentity.writeToNBT(nbttagcompound2); + //tileentity.writeToNBT(nbttagcompound2); nbttaglist3.appendTag(nbttagcompound2); } catch (Exception e) From a980e63d4a9014dbd359d829ad9e1c396ea3d948 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 8 Dec 2015 22:57:04 +0100 Subject: [PATCH 094/109] Update to localization fixed error that localization was not working in config. added more strings, and added the format paremeters with some strings. --- src/main/java/mapwriter/Mw.java | 9 +- src/main/java/mapwriter/config/Config.java | 6 +- .../config/ConfigurationHandler.java | 55 ++++++----- .../java/mapwriter/config/MapModeConfig.java | 20 ++-- .../mapwriter/config/largeMapModeConfig.java | 18 +--- .../mapwriter/config/smallMapModeConfig.java | 6 +- src/main/java/mapwriter/gui/ModGuiConfig.java | 8 +- src/main/java/mapwriter/gui/MwGui.java | 28 +++--- .../mapwriter/gui/MwGuiDimensionDialog.java | 2 +- .../java/mapwriter/gui/MwGuiMarkerDialog.java | 20 ++-- .../mapwriter/gui/MwGuiMarkerDialogNew.java | 14 +-- .../mapwriter/gui/MwGuiTeleportDialog.java | 2 +- .../gui/ScrollableColorSelector.java | 10 +- src/main/java/mapwriter/tasks/MergeTask.java | 5 +- .../mapwriter/tasks/RebuildRegionsTask.java | 3 +- src/main/java/mapwriter/util/Utils.java | 6 +- .../assets/mapwriter/lang/en_US.lang | 95 ++++++++++++------- 17 files changed, 166 insertions(+), 141 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index e63d77b2..19c37201 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -26,6 +26,7 @@ import mapwriter.util.Render; import mapwriter.util.Utils; import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; @@ -174,7 +175,7 @@ public void teleportTo(int x, int y, int z) } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + Utils.printBoth(I18n.format("mw.msg.tpdisabled")); } } @@ -187,7 +188,7 @@ public void warpTo(String name) } else { - Utils.printBoth("teleportation is disabled in mapwriter.cfg"); + Utils.printBoth(I18n.format("mw.msg.tpdisabled")); } } @@ -200,7 +201,7 @@ public void teleportToMapPos(MapView mapView, int x, int y, int z) } else { - Utils.printBoth("teleport command is set to 'warp', can only warp to markers"); + Utils.printBoth(I18n.format("mw.msg.warp.error")); } } @@ -216,7 +217,7 @@ else if (marker.dimension == this.playerDimension) } else { - Utils.printBoth("cannot teleport to marker in different dimension"); + Utils.printBoth(I18n.format("mw.msg.tp.dimError")); } } diff --git a/src/main/java/mapwriter/config/Config.java b/src/main/java/mapwriter/config/Config.java index fe28fb1a..f527c07d 100644 --- a/src/main/java/mapwriter/config/Config.java +++ b/src/main/java/mapwriter/config/Config.java @@ -6,9 +6,9 @@ public class Config { public static final String[] backgroundModeStringArray = { - "none", - "static", - "panning" + "mw.config.backgroundTextureMode.none", + "mw.config.backgroundTextureMode.static", + "mw.config.backgroundTextureMode.panning" }; // configuration options diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index e76a0181..1d991d34 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -24,35 +24,35 @@ public static void init(File configFile) } public static void loadConfig() - { - Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingDef, "mw.config.linearTextureScaling"); - Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColoursDef, "mw.config.useSavedBlockColours"); - Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabledDef, "mw.config.teleportEnabled"); - Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommandDef, "mw.config.teleportCommand"); - Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSqDef, 1, 256 * 256, "mw.config.maxChunkSaveDistSq"); - Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabledDef, "mw.config.mapPixelSnapEnabled"); - Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkersDef, 0, 1000, "mw.config.maxDeathMarkers"); - Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTickDef, 1, 500, "mw.config.chunksPerTick"); - Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverrideDef, "mw.config.saveDirOverride"); - Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabledDef, "mw.config.portNumberInWorldNameEnabled"); - Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "mw.config.undergroundMode"); - Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "mw.config.regionFileOutputEnabledSP"); - Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "mw.config.regionFileOutputEnabledMP"); - Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "mw.config.backgroundTextureMode", Config.backgroundModeStringArray); - Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "mw.config.zoomOutLevels"); - Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "mw.config.zoomInLevels"); - - Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "mw.config.textureSize"); + { + Config.linearTextureScaling = configuration.getBoolean("linearTextureScaling", Reference.catOptions, Config.linearTextureScalingDef, "", "mw.config.linearTextureScaling"); + Config.useSavedBlockColours = configuration.getBoolean("useSavedBlockColours", Reference.catOptions, Config.useSavedBlockColoursDef, "", "mw.config.useSavedBlockColours"); + Config.teleportEnabled = configuration.getBoolean("teleportEnabled", Reference.catOptions, Config.teleportEnabledDef, "", "mw.config.teleportEnabled"); + Config.teleportCommand = configuration.getString("teleportCommand", Reference.catOptions, Config.teleportCommandDef, "", "mw.config.teleportCommand"); + Config.maxChunkSaveDistSq = configuration.getInt("maxChunkSaveDistSq", Reference.catOptions, Config.maxChunkSaveDistSqDef, 1, 256 * 256, "", "mw.config.maxChunkSaveDistSq"); + Config.mapPixelSnapEnabled = configuration.getBoolean("mapPixelSnapEnabled", Reference.catOptions, Config.mapPixelSnapEnabledDef, "", "mw.config.mapPixelSnapEnabled"); + Config.maxDeathMarkers = configuration.getInt("maxDeathMarkers", Reference.catOptions, Config.maxDeathMarkersDef, 0, 1000, "", "mw.config.maxDeathMarkers"); + Config.chunksPerTick = configuration.getInt("chunksPerTick", Reference.catOptions, Config.chunksPerTickDef, 1, 500, "", "mw.config.chunksPerTick"); + Config.saveDirOverride = configuration.getString("saveDirOverride", Reference.catOptions, Config.saveDirOverrideDef, "", "mw.config.saveDirOverride"); + Config.portNumberInWorldNameEnabled = configuration.getBoolean("portNumberInWorldNameEnabled", Reference.catOptions, Config.portNumberInWorldNameEnabledDef, "", "mw.config.portNumberInWorldNameEnabled"); + Config.undergroundMode = configuration.getBoolean("undergroundMode", Reference.catOptions, Config.undergroundModeDef, "", "mw.config.undergroundMode"); + Config.regionFileOutputEnabledSP = configuration.getBoolean("regionFileOutputEnabledSP", Reference.catOptions, Config.regionFileOutputEnabledSPDef, "", "mw.config.regionFileOutputEnabledSP"); + Config.regionFileOutputEnabledMP = configuration.getBoolean("regionFileOutputEnabledMP", Reference.catOptions, Config.regionFileOutputEnabledMPDef, "", "mw.config.regionFileOutputEnabledMP"); + Config.backgroundTextureMode = configuration.getString("backgroundTextureMode", Reference.catOptions, Config.backgroundTextureModeDef, "", Config.backgroundModeStringArray, "mw.config.backgroundTextureMode"); + Config.zoomOutLevels = configuration.getInt("zoomOutLevels", Reference.catOptions, Config.zoomOutLevelsDef, 1, 256, "", "mw.config.zoomOutLevels"); + Config.zoomInLevels = -configuration.getInt("zoomInLevels", Reference.catOptions, -Config.zoomInLevelsDef, 1, 256, "", "mw.config.zoomInLevels"); - Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "mw.config.overlayModeIndex"); - Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "mw.config.overlayZoomLevel"); + Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "", "mw.config.textureSize"); + + Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "", "mw.config.overlayModeIndex"); + Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "", "mw.config.overlayZoomLevel"); - Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "mw.config.moreRealisticMap"); + Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "", "mw.config.moreRealisticMap"); - Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "mw.config.newMarkerDialog"); - Config.drawMarkersInWorld = configuration.getBoolean("drawMarkersInWorld", Reference.catOptions, Config.drawMarkersInWorldDef, "mw.config.drawMarkersInWorld"); - Config.drawMarkersNameInWorld = configuration.getBoolean("drawMarkersNameInWorld", Reference.catOptions, Config.drawMarkersNameInWorldDef, "mw.config.drawMarkersNameInWorld"); - Config.drawMarkersDistanceInWorld = configuration.getBoolean("drawMarkersDistanceInWorld", Reference.catOptions, Config.drawMarkersDistanceInWorldDef, "mw.config.drawMarkersDistanceInWorld"); + Config.newMarkerDialog = configuration.getBoolean("newMarkerDialog", Reference.catOptions, Config.newMarkerDialogDef, "", "mw.config.newMarkerDialog"); + Config.drawMarkersInWorld = configuration.getBoolean("drawMarkersInWorld", Reference.catOptions, Config.drawMarkersInWorldDef, "", "mw.config.drawMarkersInWorld"); + Config.drawMarkersNameInWorld = configuration.getBoolean("drawMarkersNameInWorld", Reference.catOptions, Config.drawMarkersNameInWorldDef, "", "mw.config.drawMarkersNameInWorld"); + Config.drawMarkersDistanceInWorld = configuration.getBoolean("drawMarkersDistanceInWorld", Reference.catOptions, Config.drawMarkersDistanceInWorldDef, "", "mw.config.drawMarkersDistanceInWorld"); Config.fullScreenMap.loadConfig(); Config.largeMap.loadConfig(); @@ -75,6 +75,9 @@ public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent public static void setMapModeDefaults() { + configuration.get(Reference.catOptions, "overlayModeIndex", Config.overlayModeIndexDef).setShowInGui(false); + configuration.get(Reference.catOptions, "overlayZoomLevel", Config.zoomInLevelsDef).setShowInGui(false); + Config.fullScreenMap.setDefaults(); Config.largeMap.setDefaults(); Config.smallMap.setDefaults(); diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index 90895764..1986a794 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -9,17 +9,17 @@ public class MapModeConfig public final String configCategory; public static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" + "mw.config.map.coordsMode.disabled", + "mw.config.map.coordsMode.small", + "mw.config.map.coordsMode.large" }; public static final String[] miniMapPositionStringArray = { - "top right", - "top left", - "bottom right", - "bottom left" + "mw.config.map.position.topRight", + "mw.config.map.position.topLeft", + "mw.config.map.position.botRight", + "mw.config.map.position.botLeft" }; public boolean enabledDef = true; @@ -53,9 +53,9 @@ public MapModeConfig(String configCategory) public void loadConfig() { // get options from config file - this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSizeDef, 1, 20, "mw.config.map.playerArrowSize"); - this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSizeDef, 1, 20, "mw.config.map.markerSize"); - this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "mw.config.map.alphaPercent"); + this.playerArrowSize = ConfigurationHandler.configuration.getInt("playerArrowSize", this.configCategory, this.playerArrowSizeDef, 1, 20, "", "mw.config.map.playerArrowSize"); + this.markerSize = ConfigurationHandler.configuration.getInt("markerSize", this.configCategory, this.markerSizeDef, 1, 20, "", "mw.config.map.markerSize"); + this.alphaPercent = ConfigurationHandler.configuration.getInt("alphaPercent", this.configCategory, this.alphaPercentDef, 0, 100, "", "mw.config.map.alphaPercent"); this.trailMarkerSize = Math.max(1, this.markerSize - 1); } diff --git a/src/main/java/mapwriter/config/largeMapModeConfig.java b/src/main/java/mapwriter/config/largeMapModeConfig.java index 7a479c30..1de6088f 100644 --- a/src/main/java/mapwriter/config/largeMapModeConfig.java +++ b/src/main/java/mapwriter/config/largeMapModeConfig.java @@ -17,11 +17,11 @@ public largeMapModeConfig(String configCategory) public void loadConfig() { super.loadConfig(); - this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabledDef, "mw.config.map.enabled"); - this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotateDef, "mw.config.map.rotate"); - this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circularDef, "mw.config.map.circular"); - this.coordsMode = ConfigurationHandler.configuration.getString("coordsMode", this.configCategory, this.coordsModeDef, "mw.config.map.coordsMode", coordsModeStringArray); - this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderModeDef, "mw.config.map.borderMode"); + this.enabled = ConfigurationHandler.configuration.getBoolean("enabled", this.configCategory, this.enabledDef, "", "mw.config.map.enabled"); + this.rotate = ConfigurationHandler.configuration.getBoolean("rotate", this.configCategory, this.rotateDef, "", "mw.config.map.rotate"); + this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circularDef, "", "mw.config.map.circular"); + this.coordsMode = ConfigurationHandler.configuration.getString("coordsMode", this.configCategory, this.coordsModeDef, "", coordsModeStringArray, "mw.config.map.coordsMode"); + this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderModeDef, "", "mw.config.map.borderMode"); } @Override @@ -36,14 +36,6 @@ public void setDefaults() this.Position = this.PositionDef; ConfigurationHandler.configuration.get(Reference.catLargeMapConfig, "enabled", this.enabled).setRequiresWorldRestart(true); - } - - @Override - public IConfigElement categoryElement(String name, String tooltip_key) - { ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); - - return new DummyCategoryElement(name, tooltip_key, new ConfigElement(ConfigurationHandler.configuration.getCategory(this.configCategory)).getChildElements()); } - } diff --git a/src/main/java/mapwriter/config/smallMapModeConfig.java b/src/main/java/mapwriter/config/smallMapModeConfig.java index a13c9c32..b93e1bb9 100644 --- a/src/main/java/mapwriter/config/smallMapModeConfig.java +++ b/src/main/java/mapwriter/config/smallMapModeConfig.java @@ -1,5 +1,6 @@ package mapwriter.config; +import mapwriter.gui.ModGuiConfig.ModBooleanEntry; import mapwriter.util.Reference; public class smallMapModeConfig extends largeMapModeConfig @@ -13,8 +14,8 @@ public smallMapModeConfig(String configCategory) public void loadConfig() { super.loadConfig(); - this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent", this.configCategory, this.heightPercentDef, 0, 100, "mw.config.map.heightPercent"); - this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "mw.config.map.Position", miniMapPositionStringArray); + this.heightPercent = ConfigurationHandler.configuration.getInt("heightPercent", this.configCategory, this.heightPercentDef, 0, 100, "", "mw.config.map.heightPercent"); + this.Position = ConfigurationHandler.configuration.getString("Position", this.configCategory, this.PositionDef, "", miniMapPositionStringArray, "mw.config.map.position"); } @Override @@ -30,5 +31,6 @@ public void setDefaults() this.PositionDef = MapModeConfig.miniMapPositionStringArray[0]; ConfigurationHandler.configuration.get(Reference.catSmallMapConfig, "enabled", this.enabledDef).setRequiresWorldRestart(true); + ConfigurationHandler.configuration.get(this.configCategory, "rotate", this.rotate).setConfigEntryClass(ModBooleanEntry.class); } } diff --git a/src/main/java/mapwriter/gui/ModGuiConfig.java b/src/main/java/mapwriter/gui/ModGuiConfig.java index 1e77595b..40857811 100644 --- a/src/main/java/mapwriter/gui/ModGuiConfig.java +++ b/src/main/java/mapwriter/gui/ModGuiConfig.java @@ -38,10 +38,10 @@ private static List getConfigElements() List list = new ArrayList(); // Add categories to config GUI - list.add(categoryElement(Reference.catOptions, "Global Options", "mymod.configgui.ctgy.general")); - list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mymod.configgui.ctgy.foo")); - list.add(Config.largeMap.categoryElement("Large map options", "mymod.configgui.ctgy.bar")); - list.add(Config.smallMap.categoryElement("Small map options", "mymod.configgui.ctgy.bar")); + list.add(categoryElement(Reference.catOptions, "Global Options", "mw.configgui.ctgy.general")); + list.add(Config.fullScreenMap.categoryElement("Fullscreen map options", "mw.configgui.ctgy.fullScreenMap")); + list.add(Config.largeMap.categoryElement("Large map options", "mw.configgui.ctgy.largeMap")); + list.add(Config.smallMap.categoryElement("Small map options", "mw.configgui.ctgy.smallMap")); return list; } diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java index fec4d32c..b5d8515a 100644 --- a/src/main/java/mapwriter/gui/MwGui.java +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -43,7 +43,7 @@ public class MwGui extends GuiScreen private String[] HelpText1 = new String[] { - "Keys:", + "mw.gui.mwgui.keys", "", " Space", " Delete", @@ -169,16 +169,16 @@ public void initLabels() { this.helpLabel = new MwGuiLabel(new String[] { - "[" + I18n.format("mw.gui.mwgui.help", new Object[0]) + "]" + "[" + I18n.format("mw.gui.mwgui.help") + "]" }, null, menuX, menuY, true, false, this.width, this.height); this.optionsLabel = new MwGuiLabel(new String[] { - "[" + I18n.format("mw.gui.mwgui.options", new Object[0]) + "]" + "[" + I18n.format("mw.gui.mwgui.options") + "]" }, null, 0, 0, true, false, this.width, this.height); this.dimensionLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); this.groupLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); this.overlayLabel = new MwGuiLabel(null, null, 0, 0, true, false, this.width, this.height); - String updateString = String.format("[" + I18n.format("mw.gui.mwgui.newversion", new Object[0]) + ": %s]", VersionCheck.getLatestVersion()); + String updateString = "[" + I18n.format("mw.gui.mwgui.newversion", VersionCheck.getLatestVersion()) + "]"; this.updateLabel = new MwGuiLabel(new String[] { updateString @@ -263,13 +263,12 @@ public void mergeMapViewToImage() this.mw.chunkManager.saveChunks(); this.mw.executor.addTask(new MergeTask(this.mw.regionManager, (int) this.mapView.getX(), (int) this.mapView.getZ(), (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), this.mapView.getDimension(), this.mw.worldDir, this.mw.worldDir.getName())); - Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", new Object[0]) + " '" + this.mw.worldDir.getAbsolutePath() + "'"); + Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.merge", this.mw.worldDir.getAbsolutePath())); } public void regenerateView() { - Utils.printBoth(String.format( - I18n.format("mw.gui.mwgui.chatmsg.regenmap.1", new Object[0]) + " %dx%d " + I18n.format("mw.gui.mwgui.chatmsg.regenmap.2", new Object[0]) + " (%d, %d)", + Utils.printBoth(I18n.format("mw.gui.mwgui.chatmsg.regenmap", (int) this.mapView.getWidth(), (int) this.mapView.getHeight(), (int) this.mapView.getMinX(), @@ -624,11 +623,11 @@ public void drawStatus(int bX, int bY, int bZ) StringBuilder builder = new StringBuilder(); if (bY != 0) { - builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, %d, %d)", bX, bY, bZ)); + builder.append(I18n.format("mw.gui.mwgui.status.cursor", bX, bY, bZ)); } else { - builder.append(String.format(I18n.format("mw.gui.mwgui.status.cursor", new Object[0]) + ": (%d, ?, %d)", bX, bZ)); + builder.append(I18n.format("mw.gui.mwgui.status.cursorNoY", bX, bZ)); } if (this.mc.theWorld != null) @@ -636,8 +635,7 @@ public void drawStatus(int bX, int bY, int bZ) if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(bX, 0, bZ)).isEmpty()) { builder.append(", "); - builder.append(I18n.format("mw.gui.mwgui.status.biome", new Object[0])); - builder.append(String.format(": %s", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); + builder.append(I18n.format("mw.gui.mwgui.status.biome", this.mc.theWorld.getBiomeGenForCoords(new BlockPos(bX, 0, bZ)).biomeName)); } } @@ -748,21 +746,21 @@ private void drawLabel(int mouseX, int mouseY, float f) { this.helpLabel.draw(); this.optionsLabel.draw(); - String dimString = String.format("[" + I18n.format("mw.gui.mwgui.dimension", new Object[0]) + ": %d]", this.mapView.getDimension()); + String dimString = "[" + I18n.format("mw.gui.mwgui.dimension",this.mapView.getDimension()) + "]"; this.dimensionLabel.setText(new String[] { dimString }, null); this.dimensionLabel.draw(); - String groupString = String.format("[" + I18n.format("mw.gui.mwgui.group", new Object[0]) + ": %s]", this.mw.markerManager.getVisibleGroupName()); + String groupString = "[" + I18n.format("mw.gui.mwgui.group.1", this.mw.markerManager.getVisibleGroupName()) + "]"; this.groupLabel.setText(new String[] { groupString }, null); this.groupLabel.draw(); - String overlayString = String.format("[" + I18n.format("mw.gui.mwgui.overlay", new Object[0]) + ": %s]", MwAPI.getCurrentProviderName()); + String overlayString = "[" + I18n.format("mw.gui.mwgui.overlay", MwAPI.getCurrentProviderName()) + "]"; this.overlayLabel.setText(new String[] { overlayString @@ -831,7 +829,7 @@ else if (m == null) String group = this.mw.markerManager.getVisibleGroupName(); if (group.equals("none")) { - group = I18n.format("mw.gui.mwgui.group", new Object[0]); + group = I18n.format("mw.gui.mwgui.group.2"); } int mx, my, mz; diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java index d509171c..e40bd27c 100644 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -18,7 +18,7 @@ public class MwGuiDimensionDialog extends MwGuiTextDialog public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) { - super(parentScreen, I18n.format("mw.gui.mwguidimensiondialog.title", new Object[0]) + ":", Integer.toString(dimension), I18n.format("mw.gui.mwguidimensiondialog.error", new Object[0])); + super(parentScreen, I18n.format("mw.gui.mwguidimensiondialog.title") + ":", Integer.toString(dimension), I18n.format("mw.gui.mwguidimensiondialog.error")); this.mw = mw; this.mapView = mapView; this.dimension = dimension; diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java index e558abb1..a742d220 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -23,7 +23,7 @@ public class MwGuiMarkerDialog extends MwGuiTextDialog public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { - super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.new", new Object[0]) + ":", markerName, I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.new") + ":", markerName, I18n.format("mw.gui.mwguimarkerdialog.error")); this.markerManager = markerManager; this.markerName = markerName; this.markerGroup = markerGroup; @@ -36,7 +36,7 @@ public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, St public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) { - super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.edit", new Object[0]) + ":", editingMarker.name, I18n.format("mw.gui.mwguimarkerdialog.error", new Object[0])); + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialog.title.edit") + ":", editingMarker.name, I18n.format("mw.gui.mwguimarkerdialog.error")); this.markerManager = markerManager; this.editingMarker = editingMarker; this.markerName = editingMarker.name; @@ -57,9 +57,9 @@ public boolean submit() this.markerName = this.getInputAsString(); if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.group", new Object[0]) + ":"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.group") + ":"; this.setText(this.markerGroup); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.group", new Object[0]); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.group"); this.state++; } break; @@ -67,9 +67,9 @@ public boolean submit() this.markerGroup = this.getInputAsString(); if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.x", new Object[0]) + ":"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.x") + ":"; this.setText("" + this.markerX); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.x", new Object[0]); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.x"); this.state++; } break; @@ -77,9 +77,9 @@ public boolean submit() this.markerX = this.getInputAsInt(); if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.y", new Object[0]) + ":"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.y") + ":"; this.setText("" + this.markerY); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.y", new Object[0]); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.y"); this.state++; } break; @@ -87,9 +87,9 @@ public boolean submit() this.markerY = this.getInputAsInt(); if (this.inputValid) { - this.title = I18n.format("mw.gui.mwguimarkerdialog.title.z", new Object[0]) + ":"; + this.title = I18n.format("mw.gui.mwguimarkerdialog.title.z") + ":"; this.setText("" + this.markerZ); - this.error = I18n.format("mw.gui.mwguimarkerdialog.error.z", new Object[0]); + this.error = I18n.format("mw.gui.mwguimarkerdialog.error.z"); this.state++; } break; diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java index 522bb653..9ef880aa 100644 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialogNew.java @@ -156,27 +156,27 @@ public void initGui() int x = ((this.width - width) + labelsWidth) / 2; int y = (this.height - (elementVSpacing * numberOfElements)) / 2; - this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName, new Object[0]), this.fontRendererObj); + this.scrollableTextBoxName = new ScrollableTextBox(x, y, width, I18n.format(this.editMarkerName), this.fontRendererObj); this.scrollableTextBoxName.setFocused(true); this.scrollableTextBoxName.setText(this.markerName); - this.scrollableTextBoxGroup = new ScrollableTextBox(x, y + MwGuiMarkerDialogNew.elementVSpacing, width, I18n.format(this.editMarkerGroup, new Object[0]), this.markerManager.groupList, this.fontRendererObj); + this.scrollableTextBoxGroup = new ScrollableTextBox(x, y + MwGuiMarkerDialogNew.elementVSpacing, width, I18n.format(this.editMarkerGroup), this.markerManager.groupList, this.fontRendererObj); this.scrollableTextBoxGroup.setText(this.markerGroup); this.scrollableTextBoxGroup.setDrawArrows(true); - this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 2), width, I18n.format(this.editMarkerX, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxX = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 2), width, I18n.format(this.editMarkerX), this.fontRendererObj); this.scrollableNumericTextBoxX.setText("" + this.markerX); this.scrollableNumericTextBoxX.setDrawArrows(true); - this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 3), width, I18n.format(this.editMarkerY, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxY = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 3), width, I18n.format(this.editMarkerY), this.fontRendererObj); this.scrollableNumericTextBoxY.setText("" + this.markerY); this.scrollableNumericTextBoxY.setDrawArrows(true); - this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 4), width, I18n.format(this.editMarkerZ, new Object[0]), this.fontRendererObj); + this.scrollableNumericTextBoxZ = new ScrollableNumericTextBox(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 4), width, I18n.format(this.editMarkerZ), this.fontRendererObj); this.scrollableNumericTextBoxZ.setText("" + this.markerZ); this.scrollableNumericTextBoxZ.setDrawArrows(true); - this.ScrollableColorSelectorColor = new ScrollableColorSelector(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 5), width, I18n.format(this.editMarkerColor, new Object[0]), this.fontRendererObj); + this.ScrollableColorSelectorColor = new ScrollableColorSelector(x, y + (MwGuiMarkerDialogNew.elementVSpacing * 5), width, I18n.format(this.editMarkerColor), this.fontRendererObj); this.ScrollableColorSelectorColor.setColor(this.colour); this.ScrollableColorSelectorColor.setDrawArrows(true); } @@ -196,7 +196,7 @@ public void drawScreen(int mouseX, int mouseY, float f) int w = (this.width * MwGuiMarkerDialogNew.dialogWidthPercent) / 100; drawRect((this.width - w) / 2, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2))) / 2) - 4, ((this.width - w) / 2) + w, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 2))) / 2) + (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1)), 0x80000000); - this.drawCenteredString(this.fontRendererObj, I18n.format(this.title, new Object[0]), (this.width) / 2, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1))) / 2) - (MwGuiMarkerDialogNew.elementVSpacing / 4), 0xffffff); + this.drawCenteredString(this.fontRendererObj, I18n.format(this.title), (this.width) / 2, ((this.height - (MwGuiMarkerDialogNew.elementVSpacing * (numberOfElements + 1))) / 2) - (MwGuiMarkerDialogNew.elementVSpacing / 4), 0xffffff); this.scrollableTextBoxName.draw(); this.scrollableTextBoxGroup.draw(); this.scrollableNumericTextBoxX.draw(); diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java index 43bb5d78..e499cb8a 100644 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -18,7 +18,7 @@ public class MwGuiTeleportDialog extends MwGuiTextDialog public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) { - super(parentScreen, I18n.format("mw.gui.mwguimarkerdialognew.title", new Object[0]) + ":", Integer.toString(y), I18n.format("mw.gui.mwguimarkerdialognew.error", new Object[0])); + super(parentScreen, I18n.format("mw.gui.mwguimarkerdialognew.title") + ":", Integer.toString(y), I18n.format("mw.gui.mwguimarkerdialognew.error")); this.mw = mw; this.mapView = mapView; this.teleportX = x; diff --git a/src/main/java/mapwriter/gui/ScrollableColorSelector.java b/src/main/java/mapwriter/gui/ScrollableColorSelector.java index 99fc85f8..aa356b0a 100644 --- a/src/main/java/mapwriter/gui/ScrollableColorSelector.java +++ b/src/main/java/mapwriter/gui/ScrollableColorSelector.java @@ -34,27 +34,27 @@ public ScrollableColorSelector(int x, int y, int width, String label, FontRender private void init() { int textboxWidth = 16; - int x1 = this.x + ScrollableField.arrowsWidth + this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) + 4; + int x1 = this.x + ScrollableField.arrowsWidth + this.fontrendererObj.getStringWidth(I18n.format(this.editGreen)) + 4; int w = (ScrollableField.arrowsWidth * 2) + this.fontrendererObj.getStringWidth("999") + textboxWidth; - this.ScrollableNumericTextBoxColourRed = new ScrollableNumericTextBox(x1, this.y, w, I18n.format(this.editRed, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourRed = new ScrollableNumericTextBox(x1, this.y, w, I18n.format(this.editRed), this.fontrendererObj); this.ScrollableNumericTextBoxColourRed.setDrawArrows(true); this.ScrollableNumericTextBoxColourRed.setMaxValue(255); this.ScrollableNumericTextBoxColourRed.setMinValue(0); - this.ScrollableNumericTextBoxColourGreen = new ScrollableNumericTextBox(x1, this.y + MwGuiMarkerDialogNew.elementVSpacing, w, I18n.format(this.editGreen, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourGreen = new ScrollableNumericTextBox(x1, this.y + MwGuiMarkerDialogNew.elementVSpacing, w, I18n.format(this.editGreen), this.fontrendererObj); this.ScrollableNumericTextBoxColourGreen.setDrawArrows(true); this.ScrollableNumericTextBoxColourGreen.setMaxValue(255); this.ScrollableNumericTextBoxColourGreen.setMinValue(0); - this.ScrollableNumericTextBoxColourBlue = new ScrollableNumericTextBox(x1, this.y + (MwGuiMarkerDialogNew.elementVSpacing * 2), w, I18n.format(this.editBlue, new Object[0]), this.fontrendererObj); + this.ScrollableNumericTextBoxColourBlue = new ScrollableNumericTextBox(x1, this.y + (MwGuiMarkerDialogNew.elementVSpacing * 2), w, I18n.format(this.editBlue), this.fontrendererObj); this.ScrollableNumericTextBoxColourBlue.setDrawArrows(true); this.ScrollableNumericTextBoxColourBlue.setMaxValue(255); this.ScrollableNumericTextBoxColourBlue.setMinValue(0); this.colourFieldX = x1 + w + 2; this.colourFieldY = this.y + 6; - this.colourFieldW = this.width - w - (ScrollableField.arrowsWidth * 2) - this.fontrendererObj.getStringWidth(I18n.format(this.editGreen, new Object[0])) - 8; + this.colourFieldW = this.width - w - (ScrollableField.arrowsWidth * 2) - this.fontrendererObj.getStringWidth(I18n.format(this.editGreen)) - 8; this.colourFieldH = MwGuiMarkerDialogNew.elementVSpacing * 2; } diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java index 4c1dc81c..25a2e743 100644 --- a/src/main/java/mapwriter/tasks/MergeTask.java +++ b/src/main/java/mapwriter/tasks/MergeTask.java @@ -5,6 +5,7 @@ import mapwriter.region.MergeToImage; import mapwriter.region.RegionManager; import mapwriter.util.Utils; +import net.minecraft.client.resources.I18n; public class MergeTask extends Task { @@ -33,11 +34,11 @@ public void run() int count = MergeToImage.merge(this.regionManager, this.x, this.z, this.w, this.h, this.dimension, this.outputDir, this.basename); if (count > 0) { - this.msg = String.format("successfully wrote merged images to directory %s", this.outputDir); + this.msg = I18n.format("mw.task.mergetask.chatmsg.merge.done", this.outputDir); } else { - this.msg = String.format("merge error: could not write images to directory %s", this.outputDir); + this.msg = I18n.format("mw.task.mergetask.chatmsg.merge.error", this.outputDir); } } diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java index 1d1cf110..fcd318f2 100644 --- a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java +++ b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java @@ -4,6 +4,7 @@ import mapwriter.region.BlockColours; import mapwriter.region.RegionManager; import mapwriter.util.Utils; +import net.minecraft.client.resources.I18n; public class RebuildRegionsTask extends Task { @@ -34,7 +35,7 @@ public void run() @Override public void onComplete() { - Utils.printBoth("rebuild task complete"); + Utils.printBoth(I18n.format("mw.task.rebuildregionstask.chatmsg.rebuild.compleet")); } @Override diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index 7f00d69f..df5b1064 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -212,7 +212,7 @@ public static String stringArrayToString(String[] arr) StringBuilder builder = new StringBuilder(); for (String s : arr) { - builder.append(I18n.format(s, new Object[0])); + builder.append(I18n.format(s)); builder.append("\n"); } return builder.toString(); @@ -229,12 +229,12 @@ public static int getMaxWidth(String[] arr, String[] arr2) if (i < arr.length) { - String s = I18n.format(arr[i], new Object[0]); + String s = I18n.format(arr[i]); w1 = fontRendererObj.getStringWidth(s); } if ((arr2 != null) && (i < arr2.length)) { - String s = I18n.format(arr2[i], new Object[0]); + String s = I18n.format(arr2[i]); w2 = fontRendererObj.getStringWidth(s); w2 += 65; } diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index 48fdbc25..36c6ad05 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -8,20 +8,30 @@ key.mw_zoom_in=Minimap zoom in key.mw_zoom_out=Minimap zoom out key.mw_underground_mode=Underground map mode +#Config +mw.configgui.ctgy.general=General +mw.configgui.ctgy.general.tooltip=Opens the General options +mw.configgui.ctgy.fullScreenMap=Fullscreen map +mw.configgui.ctgy.fullScreenMap.tooltip=Opens the Fullscreen map options +mw.configgui.ctgy.largeMap=Large map +mw.configgui.ctgy.largeMap.tooltip=Opens the Large map options +mw.configgui.ctgy.smallMap=Small map +mw.configgui.ctgy.smallMap.tooltip=Opens the Small map options + #Config Global mw.config.linearTextureScaling=Linear texture scaling enabled mw.config.linearTextureScaling.tooltip=Enabled linear texture scaling. (nearest is used otherwise) -mw.config.useSavedBlockColours= Use saved block colors -mw.config.useSavedBlockColours.tooltip= -mw.config.teleportEnabled= Teleport enabled +mw.config.useSavedBlockColours=Use saved block colors +mw.config.useSavedBlockColours.tooltip=Setting this to true will prevent the reloading of block colours, and enables you to define the colours yourself. +mw.config.teleportEnabled=Teleport enabled mw.config.teleportEnabled.tooltip=Enables teleporting to positions on the map mw.config.teleportCommand=Teleport Command mw.config.teleportCommand.tooltip=The command used to teleport the player mw.config.maxChunkSaveDistSq=Max draw distance mw.config.maxChunkSaveDistSq.tooltip=The square of the max distance from the player to map chunks at -mw.config.mapPixelSnapEnabled= Map pixel snap -mw.config.mapPixelSnapEnabled.tooltip= +mw.config.mapPixelSnapEnabled=Map pixel snap +mw.config.mapPixelSnapEnabled.tooltip=Enables rounding the texture coordinates to the nearest pixel boundary. (this makes the map look less blurry in zoom level 0 mw.config.maxDeathMarkers=Max death markers mw.config.maxDeathMarkers.tooltip=The maximum amount of death markers mw.config.chunksPerTick=Chunks per tick @@ -36,14 +46,17 @@ mw.config.regionFileOutputEnabledSP=Region file output SP mw.config.regionFileOutputEnabledSP.tooltip=set to false to disable saving region files (mca files) in single player. prevents map regen if disabled mw.config.regionFileOutputEnabledMP=Region file output MP mw.config.regionFileOutputEnabledMP.tooltip=set to false to disable saving region files (mca files) in multiplayer. prevents map regen if disabled -mw.config.backgroundTextureMode= -mw.config.backgroundTextureMode.tooltip= +mw.config.backgroundTextureMode=Background Texture Mode +mw.config.backgroundTextureMode.tooltip=Sets the type of background for the maps +mw.config.backgroundTextureMode.none=None +mw.config.backgroundTextureMode.static=Static +mw.config.backgroundTextureMode.panning=Panning mw.config.zoomOutLevels=Zoom out levels mw.config.zoomOutLevels.tooltip=Max number of steps you can zoom out. Larger values decrease performance. mw.config.zoomInLevels=Zoom in levels mw.config.zoomInLevels.tooltip=Max number of steps you can zoom in. Does not affect performance. -mw.config.textureSize= -mw.config.textureSize.tooltip= +mw.config.textureSize=Texture size +mw.config.textureSize.tooltip=Sets the texture size of the map mw.config.moreRealisticMap=Enables realistic map mw.config.moreRealisticMap.tooltip=Enable the use of a different height algorithm that makes the map look more realistic mw.config.newMarkerDialog=New Marker Dialog @@ -55,12 +68,6 @@ mw.config.drawMarkersNameInWorld.tooltip=Draws a nameplate on the location of th mw.config.drawMarkersDistanceInWorld=Show markers distance in world mw.config.drawMarkersDistanceInWorld.tooltip=Draws a distance label on the location of the marker in the world -#Config Temp -mw.config.overlayModeIndex= -mw.config.overlayModeIndex.tooltip= -mw.config.overlayZoomLevel= -mw.config.overlayZoomLevel.tooltip= - #Config map mw.config.map.enabled=Map enabled mw.config.map.enabled.tooltip=Set to false to disable this map view @@ -68,18 +75,18 @@ mw.config.map.playerArrowSize=Player arrow Size mw.config.map.playerArrowSize.tooltip=The size of the player arrow on the map mw.config.map.markerSize=Marker size mw.config.map.markerSize.tooltip=The size of markers on the map -mw.config.map.alphaPercent= Map opacity +mw.config.map.alphaPercent=Map opacity mw.config.map.alphaPercent.tooltip=Map opacity. 0-100 percent -mw.config.map.heightPercent= +mw.config.map.heightPercent=Height Percent mw.config.map.heightPercent.tooltip=The map size as a percentage of the screen height. Ignored if both Left and Right or Bottom and Top margins are set. mw.config.map.marginTop=Top margin -mw.config.map.marginTop.tooltip= +mw.config.map.marginTop.tooltip=Distance in pixels from top of the screen mw.config.map.marginBottom=Bottom margin -mw.config.map.marginBottom.tooltip= +mw.config.map.marginBottom.tooltip=Distance in pixels from bottem of the screen mw.config.map.marginLeft=Left margin -mw.config.map.marginLeft.tooltip= +mw.config.map.marginLeft.tooltip=Distance in pixels from left of the screen mw.config.map.marginRight=Right margin -mw.config.map.marginRight.tooltip= +mw.config.map.marginRight.tooltip=Distance in pixels from right of the screen mw.config.map.rotate=Rotate map mw.config.map.rotate.tooltip=Set to true to rotate the map, only possible in circular mode mw.config.map.circular=Circular map @@ -90,17 +97,27 @@ mw.config.map.borderMode=Draw border mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map mw.config.map.trailMarkerSize=Trail marker size mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map - -mw.config.coordsMode= Coordinates mode -mw.config.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap +mw.config.map.coordsMode=Coordinates mode +mw.config.map.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap +mw.config.map.coordsMode.disabled=Disabled +mw.config.map.coordsMode.small=Small +mw.config.map.coordsMode.large=Large +mw.config.map.position=Map position +mw.config.map.position.tooltip=Location of the map +mw.config.map.position.topRight=Top Right +mw.config.map.position.topLeft=Top Left +mw.config.map.position.botRight=Bottom Right +mw.config.map.position.botLeft=Bottom Left #Gui mw.gui.mwgui.help=Help mw.gui.mwgui.options=Options -mw.gui.mwgui.dimension=dimension -mw.gui.mwgui.group=group -mw.gui.mwgui.overlay=overlay -mw.gui.mwgui.newversion=New version +mw.gui.mwgui.dimension=dimension: %d +mw.gui.mwgui.group.1=group: %s +mw.gui.mwgui.group.2=group +mw.gui.mwgui.overlay=overlay: %s +mw.gui.mwgui.keys=Keys +mw.gui.mwgui.newversion=New version: %s mw.gui.mwgui.helptext.1=Left click drag or arrow keys pan the map. mw.gui.mwgui.helptext.2=Mouse wheel or Page Up/Down zooms map. mw.gui.mwgui.helptext.3=Right click map to create a new marker. @@ -121,12 +138,12 @@ mw.gui.mwgui.helptext.savepng=Save PNG of visible map area mw.gui.mwgui.helptext.regenerate=Regenerate visible map area from region files mw.gui.mwgui.helptext.undergroundmap=Underground map mode mw.gui.mwgui.helptext.markerlist=Shows the markerlist -mw.gui.mwgui.status.biome=biome -mw.gui.mwgui.status.cursor=cursor -mw.gui.mwgui.chatmsg.regenmap.1=regenerating +mw.gui.mwgui.status.biome=biome: %s +mw.gui.mwgui.status.cursor=cursor: (%d, %d, %d) +mw.gui.mwgui.status.cursorNoY=cursor: (%d, ?, %d) mw.gui.mwgui.group=group -mw.gui.mwgui.chatmsg.regenmap.2=blocks starting from -mw.gui.mwgui.chatmsg.merge=merging to +mw.gui.mwgui.chatmsg.regenmap=regenerating %dx%d blocks starting from (%d, %d) +mw.gui.mwgui.chatmsg.merge=merging to '%s' mw.gui.mwguidimensiondialog.title=Set dimension to mw.gui.mwguidimensiondialog.error=invalid dimension @@ -156,4 +173,14 @@ mw.gui.mwguimarkerdialognew.error=invalid height mw.gui.ScrollableColorSelector.Red=Red mw.gui.ScrollableColorSelector.Green=Green -mw.gui.ScrollableColorSelector.Blue=Blue \ No newline at end of file +mw.gui.ScrollableColorSelector.Blue=Blue + +#task +mw.task.mergetask.chatmsg.merge.done=successfully wrote merged images to directory %s +mw.task.mergetask.chatmsg.merge.error=merge error: could not write images to directory %s +mw.task.rebuildregionstask.chatmsg.rebuild.compleet=rebuild task complete + +#messages +mw.msg.tp.disabled=teleportation is disabled in config +mw.msg.tp.dimError=cannot teleport to marker in different dimension +mw.msg.warp.error=teleport command is set to 'warp', can only warp to markers \ No newline at end of file From 5404945321b1bf28cc02146a1214ddfa1a471118 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 7 Jan 2016 00:11:20 +0100 Subject: [PATCH 095/109] add option for biome name under the minimap --- src/main/java/mapwriter/Mw.java | 12 ++++- .../java/mapwriter/config/MapModeConfig.java | 2 + .../mapwriter/config/largeMapModeConfig.java | 1 + .../mapwriter/config/smallMapModeConfig.java | 1 + src/main/java/mapwriter/map/MapRenderer.java | 52 ++++++++++++++++--- .../assets/mapwriter/lang/en_US.lang | 4 +- 6 files changed, 62 insertions(+), 10 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 19c37201..1eaa8e51 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -29,6 +29,7 @@ import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; @@ -56,6 +57,7 @@ public class Mw public int playerXInt = 0; public int playerYInt = 0; public int playerZInt = 0; + public String playerBiome = ""; public double playerHeading = 0.0; public int playerDimension = 0; public float mapRotationDegrees = 0.0f; @@ -143,7 +145,15 @@ public void updatePlayer() this.playerXInt = (int) Math.floor(this.playerX); this.playerYInt = (int) Math.floor(this.playerY); this.playerZInt = (int) Math.floor(this.playerZ); - + + if (this.mc.theWorld != null) + { + if (!this.mc.theWorld.getChunkFromBlockCoords(new BlockPos(this.playerX, 0, this.playerZ)).isEmpty()) + { + this.playerBiome = this.mc.theWorld.getBiomeGenForCoords(new BlockPos(this.playerX, 0, this.playerZ)).biomeName; + } + } + // rotationYaw of 0 points due north, we want it to point due east // instead // so add pi/2 radians (90 degrees) diff --git a/src/main/java/mapwriter/config/MapModeConfig.java b/src/main/java/mapwriter/config/MapModeConfig.java index 1986a794..3f72c761 100644 --- a/src/main/java/mapwriter/config/MapModeConfig.java +++ b/src/main/java/mapwriter/config/MapModeConfig.java @@ -44,6 +44,8 @@ public class MapModeConfig public int heightPercent = this.heightPercentDef; public String PositionDef = "FullScreen"; public String Position = this.PositionDef; + public String biomeModeDef = coordsModeStringArray[0]; + public String biomeMode = this.biomeModeDef; public MapModeConfig(String configCategory) { diff --git a/src/main/java/mapwriter/config/largeMapModeConfig.java b/src/main/java/mapwriter/config/largeMapModeConfig.java index 1de6088f..bac1d3ea 100644 --- a/src/main/java/mapwriter/config/largeMapModeConfig.java +++ b/src/main/java/mapwriter/config/largeMapModeConfig.java @@ -22,6 +22,7 @@ public void loadConfig() this.circular = ConfigurationHandler.configuration.getBoolean("circular", this.configCategory, this.circularDef, "", "mw.config.map.circular"); this.coordsMode = ConfigurationHandler.configuration.getString("coordsMode", this.configCategory, this.coordsModeDef, "", coordsModeStringArray, "mw.config.map.coordsMode"); this.borderMode = ConfigurationHandler.configuration.getBoolean("borderMode", this.configCategory, this.borderModeDef, "", "mw.config.map.borderMode"); + this.biomeMode = ConfigurationHandler.configuration.getString("biomeMode", this.configCategory, this.biomeModeDef, "", coordsModeStringArray, "mw.config.map.biomeMode"); } @Override diff --git a/src/main/java/mapwriter/config/smallMapModeConfig.java b/src/main/java/mapwriter/config/smallMapModeConfig.java index b93e1bb9..6257f5b8 100644 --- a/src/main/java/mapwriter/config/smallMapModeConfig.java +++ b/src/main/java/mapwriter/config/smallMapModeConfig.java @@ -24,6 +24,7 @@ public void setDefaults() this.rotateDef = true; this.circularDef = true; this.coordsModeDef = coordsModeStringArray[1]; + this.biomeModeDef = coordsModeStringArray[0]; this.borderModeDef = true; this.playerArrowSizeDef = 4; this.markerSizeDef = 3; diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index d60c425f..f63fefd5 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -13,6 +13,8 @@ import mapwriter.util.Reference; import mapwriter.util.Render; import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.BlockPos; import org.lwjgl.opengl.GL11; @@ -24,7 +26,8 @@ public class MapRenderer // accessed by the MwGui to check whether the mouse cursor is near the // player arrow on the rendered map public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - + private int textOffset = 12; + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { this.mw = mw; @@ -219,6 +222,14 @@ private void drawIcons() this.drawPlayerArrow(); } + private void drawStatusText() + { + this.textOffset = 12; + drawCoords(); + drawBiomeName(); + drawUndergroundMode(); + } + private void drawCoords() { // draw coordinates @@ -228,19 +239,46 @@ private void drawCoords() GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); if (this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[1])) { - GlStateManager.scale(0.5f, 0.5f, 1.0f); + GlStateManager.scale(0.5f, 0.5f, 1.0f); + this.textOffset = (int)(this.textOffset * 0.5f); } - int offset = 0; Render.drawCentredString(0, 0, this.mapMode.textColour, "%d, %d, %d", this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); - offset += 12; - if (Config.undergroundMode) + this.mapMode.textY += this.textOffset; + GlStateManager.popMatrix(); + } + } + + private void drawBiomeName() + { + if (!this.mapMode.config.biomeMode.equals(MapModeConfig.coordsModeStringArray[0])) + { + GlStateManager.pushMatrix(); + GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); + if (this.mapMode.config.biomeMode.equals(MapModeConfig.coordsModeStringArray[1])) { - Render.drawCentredString(0, offset, this.mapMode.textColour, "underground mode"); + GlStateManager.scale(0.5f, 0.5f, 1.0f); + this.textOffset = (int)(this.textOffset * 0.5f); } + Render.drawCentredString(0, 0, this.mapMode.textColour, this.mw.playerBiome); + this.mapMode.textY += this.textOffset; GlStateManager.popMatrix(); } } + private void drawUndergroundMode() + { + if (Config.undergroundMode) + { + GlStateManager.pushMatrix(); + GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); + GlStateManager.scale(0.5f, 0.5f, 1.0f); + this.textOffset = (int)(this.textOffset * 0.5f); + Render.drawCentredString(0, 0, this.mapMode.textColour, "underground mode"); + this.mapMode.textY += this.textOffset; + GlStateManager.popMatrix(); + } + } + private IMwDataProvider drawOverlay() { // draw overlays from registered providers @@ -284,7 +322,7 @@ public void draw() } this.drawIcons(); - this.drawCoords(); + this.drawStatusText(); // some shader mods seem to need depth testing re-enabled GL11.glEnable(GL11.GL_DEPTH_TEST); diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang index 36c6ad05..be6d5914 100644 --- a/src/main/resources/assets/mapwriter/lang/en_US.lang +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -91,14 +91,14 @@ mw.config.map.rotate=Rotate map mw.config.map.rotate.tooltip=Set to true to rotate the map, only possible in circular mode mw.config.map.circular=Circular map mw.config.map.circular.tooltip=True = Circular map, false = square map -mw.config.map.coordsEnabled=Enable coordinates -mw.config.map.coordsEnabled.tooltip=set to true to display coordinates under map mw.config.map.borderMode=Draw border mw.config.map.borderMode.tooltip=Set to true to draw the borders around the map mw.config.map.trailMarkerSize=Trail marker size mw.config.map.trailMarkerSize.tooltip=The size of trail markers on the map mw.config.map.coordsMode=Coordinates mode mw.config.map.coordsMode.tooltip=Switch between no,small or large coordinates under the minimap +mw.config.map.biomeMode=Biome mode +mw.config.map.biomeMode.tooltip=Switch between no,small or large biome name under the minimap mw.config.map.coordsMode.disabled=Disabled mw.config.map.coordsMode.small=Small mw.config.map.coordsMode.large=Large From f532ca1ceea2e87b3e23fc8b9186abfef2921944 Mon Sep 17 00:00:00 2001 From: Vectron Date: Fri, 8 Jan 2016 18:41:02 +0100 Subject: [PATCH 096/109] skip blocks with rendertype -1 this removes air and barrier blocks from the map --- src/main/java/mapwriter/BlockColourGen.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java index dad1bcdd..cfdbc7ca 100644 --- a/src/main/java/mapwriter/BlockColourGen.java +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -111,17 +111,14 @@ public static void genBlockColours(BlockColours bc) { Block block = (Block) oblock; int blockID = Block.getIdFromBlock(block); - if (blockID == 0) - { - continue; - } + for (int dv = 0; dv < 16; dv++) { // int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); int blockColour = 0; - if (block != null) + if (block != null && block.getRenderType() != -1) { TextureAtlasSprite icon = null; From f9cfbf249a0818b83898a12e48b105a94dba4c12 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 10 Jan 2016 20:18:32 +0100 Subject: [PATCH 097/109] added the mod version to the blockcolour files, so we can regen if there a new version installed --- src/main/java/mapwriter/Mw.java | 7 ++-- .../java/mapwriter/region/BlockColours.java | 32 ++++++++++++++++++- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java index 1eaa8e51..005eb434 100644 --- a/src/main/java/mapwriter/Mw.java +++ b/src/main/java/mapwriter/Mw.java @@ -264,8 +264,9 @@ public void saveBlockColours(BlockColours bc) public void reloadBlockColours() { BlockColours bc = new BlockColours(); - File f = new File(this.configDir, Reference.blockColourSaveFileName); - if (Config.useSavedBlockColours && f.isFile()) + File f = new File(this.configDir, Reference.blockColourSaveFileName); + + if (Config.useSavedBlockColours && f.isFile() && bc.CheckFileVersion(f)) { // load block colours from file Logging.logInfo("loading block colours from %s", f); @@ -283,7 +284,7 @@ public void reloadBlockColours() } this.blockColours = bc; } - + public void reloadMapTexture() { this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java index 74d2dc8b..72fc1b54 100644 --- a/src/main/java/mapwriter/region/BlockColours.java +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -5,6 +5,7 @@ import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; +import java.io.RandomAccessFile; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; @@ -16,6 +17,7 @@ import java.util.Scanner; import mapwriter.util.Logging; +import mapwriter.util.Reference; import mapwriter.util.Render; import net.minecraft.block.Block; @@ -440,6 +442,10 @@ else if (lineSplit[0].equals("block") && (lineSplit.length == 4)) else if (lineSplit[0].equals("blocktype") && (lineSplit.length == 4)) { this.loadBlockTypeLine(lineSplit); + } + else if (lineSplit[0].equals("version:")) + { + } else { @@ -611,6 +617,7 @@ public void saveToFile(File f) try { fout = new OutputStreamWriter(new FileOutputStream(f)); + fout.write(String.format("version: %s\n", Reference.VERSION)); this.saveBiomes(fout); this.saveBlockTypes(fout); this.saveBlocks(fout); @@ -642,7 +649,8 @@ public static void writeOverridesFile(File f) try { fout = new OutputStreamWriter(new FileOutputStream(f)); - + fout.write(String.format("version: %s\n", Reference.VERSION)); + fout.write("block minecraft:yellow_flower * 60ffff00 # make dandelions more yellow\n" + "block minecraft:red_flower 0 60ff0000 # make poppy more red\n" + "block minecraft:red_flower 1 601c92d6 # make Blue Orchid more red\n" + "block minecraft:red_flower 2 60b865fb # make Allium more red\n" + "block minecraft:red_flower 3 60e4eaf2 # make Azure Bluet more red\n" + "block minecraft:red_flower 4 60d33a17 # make Red Tulip more red\n" + "block minecraft:red_flower 5 60e17124 # make Orange Tulip more red\n" + "block minecraft:red_flower 6 60ffffff # make White Tulip more red\n" + "block minecraft:red_flower 7 60eabeea # make Pink Tulip more red\n" @@ -688,6 +696,28 @@ public static void writeOverridesFile(File f) } } + public boolean CheckFileVersion(File fn) + { + String lineData = ""; + try + { + RandomAccessFile inFile = new RandomAccessFile(fn,"rw"); + lineData = inFile.readLine(); + inFile.close(); + } + catch(IOException ex) + { + System.err.println(ex.getMessage()); + } + + if (lineData.equals(String.format("version: %s", Reference.VERSION))) + { + return true; + } + + return false; + } + public class BlockData { public int color = 0; From 5a7d470391d88d79b7e2cddd12b66ea3e00a44c4 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 10 Jan 2016 23:51:58 +0100 Subject: [PATCH 098/109] Initial update to 1.8.8 --- build.gradle | 15 +++++++-------- build.properties | 8 ++++---- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/build.gradle b/build.gradle index 4bfeb382..a5f22542 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -/* + // For those who want the bleeding edge buildscript { repositories { @@ -12,20 +12,19 @@ buildscript { } } dependencies { - //classpath 'net.minecraftforge.gradle:ForgeGradle:2.0-SNAPSHOT' - //classpath 'com.matthewprenger:CurseGradle:1.0.3-SNAPSHOT' + classpath 'net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT' + //classpath 'com.matthewprenger:CurseGradle:1.0.5-SNAPSHOT' } } -*/ // for people who want stable plugins { - id "net.minecraftforge.gradle.forge" version "2.0.2" - id 'com.matthewprenger.cursegradle' version '1.0.3' + //id "net.minecraftforge.gradle.forge" version "2.0.2" + id 'com.matthewprenger.cursegradle' version '1.0.4' } -//apply plugin: 'net.minecraftforge.gradle.forge' -//apply plugin: 'com.matthewprenger.cursegradle' +apply plugin: 'net.minecraftforge.gradle.forge' +apply plugin: 'com.matthewprenger.cursegradle' repositories { mavenLocal() diff --git a/build.properties b/build.properties index a5b65216..8d1925db 100644 --- a/build.properties +++ b/build.properties @@ -1,8 +1,8 @@ mod_name=MapWriter mod_group=vectron -mc_version=1.8 -forge_version=11.14.4.1563 -mcp_version=snapshot_20151123 +mc_version=1.8.8 +forge_version=11.15.0.1655 +mcp_version=snapshot_20160110 mod_version=2.2.12 curse_project_id=231387 -release_type=release \ No newline at end of file +release_type=beta \ No newline at end of file From 6e1f306803e6730a2cf3ee622c34220792f95983 Mon Sep 17 00:00:00 2001 From: Vectron Date: Sun, 10 Jan 2016 23:53:14 +0100 Subject: [PATCH 099/109] all rendering stuff changed, ready for beta deploy --- build.properties | 2 +- src/main/java/mapwriter/gui/MwGuiSlot.java | 55 ++++--- src/main/java/mapwriter/map/Marker.java | 13 ++ .../java/mapwriter/map/MarkerManager.java | 138 +++++++++--------- .../java/mapwriter/map/mapmode/MapMode.java | 2 +- src/main/java/mapwriter/util/Render.java | 51 +++---- 6 files changed, 139 insertions(+), 122 deletions(-) diff --git a/build.properties b/build.properties index 8d1925db..6604689b 100644 --- a/build.properties +++ b/build.properties @@ -3,6 +3,6 @@ mod_group=vectron mc_version=1.8.8 forge_version=11.15.0.1655 mcp_version=snapshot_20160110 -mod_version=2.2.12 +mod_version=2.3.12 curse_project_id=231387 release_type=beta \ No newline at end of file diff --git a/src/main/java/mapwriter/gui/MwGuiSlot.java b/src/main/java/mapwriter/gui/MwGuiSlot.java index 0eaf518b..254489d8 100644 --- a/src/main/java/mapwriter/gui/MwGuiSlot.java +++ b/src/main/java/mapwriter/gui/MwGuiSlot.java @@ -6,11 +6,13 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public abstract class MwGuiSlot @@ -305,26 +307,23 @@ public void drawScreen(int mouseXIn, int mouseYIn, float f) i2 = this.top; } // draw the scrollbar - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(0, 255); - worldrenderer.addVertexWithUV(k, this.bottom, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV(l, this.bottom, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV(l, this.top, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV(k, this.top, 0.0D, 0.0D, 0.0D); + worldrenderer.begin(GL11.GL_QUADS , DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(k, this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(l, this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(l, this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(k, this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(8421504, 255); - worldrenderer.addVertexWithUV(k, i2 + l1, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV(l, i2 + l1, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV(l, i2, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV(k, i2, 0.0D, 0.0D, 0.0D); + worldrenderer.begin(GL11.GL_QUADS , DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(k, i2 + l1, 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(l, i2 + l1, 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(l, i2, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(k, i2, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(12632256, 255); - worldrenderer.addVertexWithUV(k, (i2 + l1) - 1, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV(l - 1, (i2 + l1) - 1, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV(l - 1, i2, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV(k, i2, 0.0D, 0.0D, 0.0D); + worldrenderer.begin(GL11.GL_QUADS , DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(k, (i2 + l1) - 1, 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos(l - 1, (i2 + l1) - 1, 0.0D).tex(1.0D, 1.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos(l - 1, i2, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos(k, i2, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex(); tessellator.draw(); } @@ -504,17 +503,15 @@ protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.disableTexture2D(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorOpaque_I(8421504); - worldrenderer.addVertexWithUV(xLeft, yTotal + slotHeight, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV(xRight, yTotal + slotHeight, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV(xRight, (yTotal), 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV(xLeft, (yTotal), 0.0D, 0.0D, 0.0D); - worldrenderer.setColorOpaque_I(0); - worldrenderer.addVertexWithUV(xLeft + 1, (yTotal + slotHeight) - 1, 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV(xRight - 1, (yTotal + slotHeight) - 1, 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV(xRight - 1, yTotal + 1, 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV(xLeft + 1, yTotal + 1, 0.0D, 0.0D, 0.0D); + worldrenderer.begin( GL11.GL_QUADS , DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(xLeft, yTotal + slotHeight, 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(xRight, yTotal + slotHeight, 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(xRight, (yTotal), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(xLeft, (yTotal), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos(xLeft + 1, (yTotal + slotHeight) - 1, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(xRight - 1, (yTotal + slotHeight) - 1, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(xRight - 1, yTotal + 1, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(xLeft + 1, yTotal + 1, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); } diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java index 6b409cfa..d42eae13 100644 --- a/src/main/java/mapwriter/map/Marker.java +++ b/src/main/java/mapwriter/map/Marker.java @@ -85,4 +85,17 @@ public double getDistanceToMarker(Entity entityIn) double d2 = this.z - entityIn.posZ; return MathHelper.sqrt_double((d0 * d0) + (d1 * d1) + (d2 * d2)); } + + public float getRed() + { + return (((colour >> 16) & 0xff) / 255.0f); + } + public float getGreen() + { + return (((colour >> 8) & 0xff) / 255.0f); + } + public float getBlue() + { + return (((colour) & 0xff) / 255.0f); + } } \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index 60fb5973..b4e25b9c 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -18,6 +18,7 @@ import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraftforge.common.config.Configuration; import org.lwjgl.opengl.GL11; @@ -394,69 +395,71 @@ public void drawBeam(Marker m, float partialTicks) GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.depthMask(false); - worldrenderer.startDrawingQuads(); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); // size of the square from middle to edge double d4 = 0.2D; - double d5 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); - double d6 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); - double d7 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); - double d8 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); - double d9 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); + double d5 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); + double d6 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); + double d7 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); + double d8 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); + double d9 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); double d10 = 0.5D + (Math.sin(d3 + 3.9269908169872414D) * d4); - double d11 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); - double d12 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); - - worldrenderer.setColorRGBA_I(m.colour, 50); - - worldrenderer.addVertex(x + d5, y + d17, z + d6); - worldrenderer.addVertex(x + d5, y, z + d6); - worldrenderer.addVertex(x + d7, y, z + d8); - worldrenderer.addVertex(x + d7, y + d17, z + d8); - worldrenderer.addVertex(x + d11, y + d17, z + d12); - worldrenderer.addVertex(x + d11, y, z + d12); - worldrenderer.addVertex(x + d9, y, z + d10); - worldrenderer.addVertex(x + d9, y + d17, z + d10); - worldrenderer.addVertex(x + d7, y + d17, z + d8); - worldrenderer.addVertex(x + d7, y, z + d8); - worldrenderer.addVertex(x + d11, y, z + d12); - worldrenderer.addVertex(x + d11, y + d17, z + d12); - worldrenderer.addVertex(x + d9, y + d17, z + d10); - worldrenderer.addVertex(x + d9, y, z + d10); - worldrenderer.addVertex(x + d5, y, z + d6); - worldrenderer.addVertex(x + d5, y + d17, z + d6); + double d11 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); + double d12 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); + + float fRed = m.getRed(); + float fGreen = m.getGreen(); + float fBlue = m.getBlue(); + float fAlpha = 0.125f; + + worldrenderer.pos(x + d5, y + d17, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y + d17, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y + d17, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y + d17, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y + d17, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y + d17, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y + d17, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y + d17, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(m.colour, 50); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); // size of the square from middle to edge d4 = 0.5D; - d5 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); - d6 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); - d7 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); - d8 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); - d9 = 0.5D + (Math.sin(d3 + 3.9269908169872414D) * d4); - d10 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); - d11 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); - d12 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); - - worldrenderer.addVertex(x + d5, y + d17, z + d6); - worldrenderer.addVertex(x + d5, y, z + d6); - worldrenderer.addVertex(x + d7, y, z + d8); - worldrenderer.addVertex(x + d7, y + d17, z + d8); - worldrenderer.addVertex(x + d11, y + d17, z + d12); - worldrenderer.addVertex(x + d11, y, z + d12); - worldrenderer.addVertex(x + d9, y, z + d10); - worldrenderer.addVertex(x + d9, y + d17, z + d10); - worldrenderer.addVertex(x + d7, y + d17, z + d8); - worldrenderer.addVertex(x + d7, y, z + d8); - worldrenderer.addVertex(x + d11, y, z + d12); - worldrenderer.addVertex(x + d11, y + d17, z + d12); - worldrenderer.addVertex(x + d9, y + d17, z + d10); - worldrenderer.addVertex(x + d9, y, z + d10); - worldrenderer.addVertex(x + d5, y, z + d6); - worldrenderer.addVertex(x + d5, y + d17, z + d6); + d5 = 0.5D + (Math.sin(d3 + 2.356194490192345D) * d4); + d6 = 0.5D + (Math.cos(d3 + 2.356194490192345D) * d4); + d7 = 0.5D + (Math.sin(d3 + (Math.PI / 4D)) * d4); + d8 = 0.5D + (Math.cos(d3 + (Math.PI / 4D)) * d4); + d9 = 0.5D + (Math.sin(d3 + 3.9269908169872414D) * d4); + d10 = 0.5D + (Math.cos(d3 + 3.9269908169872414D) * d4); + d11 = 0.5D + (Math.sin(d3 + 5.497787143782138D) * d4); + d12 = 0.5D + (Math.cos(d3 + 5.497787143782138D) * d4); + + worldrenderer.pos(x + d5, y + d17, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y + d17, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y + d17, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y + d17, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y + d17, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d7, y, z + d8).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d11, y + d17, z + d12).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y + d17, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d9, y, z + d10).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(x + d5, y + d17, z + d6).color(fRed, fGreen, fBlue, fAlpha).endVertex(); tessellator.draw(); GlStateManager.enableLighting(); @@ -477,6 +480,11 @@ public void drawLabel(Marker m) double y = (0.5D + m.y) - TileEntityRendererDispatcher.staticPlayerY; double z = (0.5D + m.z) - TileEntityRendererDispatcher.staticPlayerZ; + float fRed = m.getRed(); + float fGreen = m.getGreen(); + float fBlue = m.getBlue(); + float fAlpha = 0.2f; + double distance = m.getDistanceToMarker(renderManager.livingPlayer); String strText = m.name; @@ -507,20 +515,18 @@ public void drawLabel(Marker m) GlStateManager.disableTexture2D(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(m.colour, 64); - worldrenderer.addVertex(-strTextWidth - 1, (-1), 0.0D); - worldrenderer.addVertex(-strTextWidth - 1, (8), 0.0D); - worldrenderer.addVertex(strTextWidth + 1, (8), 0.0D); - worldrenderer.addVertex(strTextWidth + 1, (-1), 0.0D); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(-strTextWidth - 1, (-1), 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(-strTextWidth - 1, (8), 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(strTextWidth + 1, (8), 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(strTextWidth + 1, (-1), 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); tessellator.draw(); - worldrenderer.startDrawingQuads(); - worldrenderer.setColorRGBA_I(m.colour, 64); - worldrenderer.addVertex(-strDistanceWidth - 1, -1 + offstet, 0.0D); - worldrenderer.addVertex(-strDistanceWidth - 1, 8 + offstet, 0.0D); - worldrenderer.addVertex(strDistanceWidth + 1, 8 + offstet, 0.0D); - worldrenderer.addVertex(strDistanceWidth + 1, -1 + offstet, 0.0D); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(-strDistanceWidth - 1, -1 + offstet, 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(-strDistanceWidth - 1, 8 + offstet, 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(strDistanceWidth + 1, 8 + offstet, 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); + worldrenderer.pos(strDistanceWidth + 1, -1 + offstet, 0.0D).color(fRed, fGreen, fBlue, fAlpha).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java index 4c78c657..cca29090 100644 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -58,7 +58,7 @@ public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) public void setScreenRes() { Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + ScaledResolution sRes = new ScaledResolution(mc); this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); } diff --git a/src/main/java/mapwriter/util/Render.java b/src/main/java/mapwriter/util/Render.java index ecaa7407..d1c43fd8 100644 --- a/src/main/java/mapwriter/util/Render.java +++ b/src/main/java/mapwriter/util/Render.java @@ -5,6 +5,7 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -170,11 +171,11 @@ public static void drawTexturedRect(double x, double y, double w, double h, doub GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawingQuads(); - renderer.addVertexWithUV(x + w, y, zDepth, u2, v1); - renderer.addVertexWithUV(x, y, zDepth, u1, v1); - renderer.addVertexWithUV(x, y + h, zDepth, u1, v2); - renderer.addVertexWithUV(x + w, y + h, zDepth, u2, v2); + renderer.begin(GL11.GL_QUADS , DefaultVertexFormats.POSITION_TEX );; + renderer.pos(x + w, y, zDepth).tex(u2, v1).endVertex(); + renderer.pos(x, y, zDepth).tex(u1, v1).endVertex(); + renderer.pos(x, y + h, zDepth).tex(u1, v2).endVertex(); + renderer.pos(x + w, y + h, zDepth).tex(u2, v2).endVertex(); // renderer.finishDrawing(); tessellator.draw(); GlStateManager.disableBlend(); @@ -195,11 +196,11 @@ public static void drawArrow(double x, double y, double angle, double length) GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_FAN); - renderer.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); - renderer.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); - renderer.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); - renderer.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); + renderer.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION); + renderer.pos(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth).endVertex(); + renderer.pos(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth).endVertex(); + renderer.pos(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth).endVertex(); + renderer.pos(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth).endVertex(); // renderer.finishDrawing(); tessellator.draw(); GlStateManager.enableTexture2D(); @@ -213,10 +214,10 @@ public static void drawTriangle(double x1, double y1, double x2, double y2, doub GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLES); - renderer.addVertex(x1, y1, zDepth); - renderer.addVertex(x2, y2, zDepth); - renderer.addVertex(x3, y3, zDepth); + renderer.begin(GL11.GL_TRIANGLES, DefaultVertexFormats.POSITION); + renderer.pos(x1, y1, zDepth).endVertex(); + renderer.pos(x2, y2, zDepth).endVertex(); + renderer.pos(x3, y3, zDepth).endVertex(); // renderer.finishDrawing(); tessellator.draw(); GlStateManager.enableTexture2D(); @@ -230,11 +231,11 @@ public static void drawRect(double x, double y, double w, double h) GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawingQuads(); - renderer.addVertex(x + w, y, zDepth); - renderer.addVertex(x, y, zDepth); - renderer.addVertex(x, y + h, zDepth); - renderer.addVertex(x + w, y + h, zDepth); + renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION); + renderer.pos(x + w, y, zDepth).endVertex(); + renderer.pos(x, y, zDepth).endVertex(); + renderer.pos(x, y + h, zDepth).endVertex(); + renderer.pos(x + w, y + h, zDepth).endVertex(); // renderer.finishDrawing(); tessellator.draw(); GlStateManager.enableTexture2D(); @@ -248,15 +249,15 @@ public static void drawCircle(double x, double y, double r) GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_FAN); - renderer.addVertex(x, y, zDepth); + renderer.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION); + renderer.pos(x, y, zDepth).endVertex(); // for some the circle is only drawn if theta is decreasing rather than // ascending double end = Math.PI * 2.0; double incr = end / circleSteps; for (double theta = -incr; theta < end; theta += incr) { - renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + renderer.pos(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth).endVertex(); } // renderer.finishDrawing(); tessellator.draw(); @@ -271,7 +272,7 @@ public static void drawCircleBorder(double x, double y, double r, double width) GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer renderer = tessellator.getWorldRenderer(); - renderer.startDrawing(GL11.GL_TRIANGLE_STRIP); + renderer.begin(GL11.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION); // for some the circle is only drawn if theta is decreasing rather than // ascending double end = Math.PI * 2.0; @@ -279,8 +280,8 @@ public static void drawCircleBorder(double x, double y, double r, double width) double r2 = r + width; for (double theta = -incr; theta < end; theta += incr) { - renderer.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - renderer.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); + renderer.pos(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth).endVertex(); + renderer.pos(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth).endVertex(); } // renderer.finishDrawing(); tessellator.draw(); From 93dd77a719f1e9bb2f38280f9ba51b49999b585c Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 18 Jan 2016 16:21:28 +0100 Subject: [PATCH 100/109] Update To 1.8.9 --- build.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build.properties b/build.properties index 6604689b..9e5c395e 100644 --- a/build.properties +++ b/build.properties @@ -1,8 +1,8 @@ mod_name=MapWriter mod_group=vectron -mc_version=1.8.8 -forge_version=11.15.0.1655 -mcp_version=snapshot_20160110 +mc_version=1.8.9 +forge_version=11.15.0.1707 +mcp_version=snapshot_20160118 mod_version=2.3.12 curse_project_id=231387 release_type=beta \ No newline at end of file From 93019af6159d7ee6a3760c38859e53dcfee12d56 Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 18 Jan 2016 16:21:58 +0100 Subject: [PATCH 101/109] NPE fix when connecting to realms --- src/main/java/mapwriter/util/Utils.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/mapwriter/util/Utils.java b/src/main/java/mapwriter/util/Utils.java index df5b1064..a8230e97 100644 --- a/src/main/java/mapwriter/util/Utils.java +++ b/src/main/java/mapwriter/util/Utils.java @@ -18,6 +18,7 @@ import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.resources.I18n; +import net.minecraft.realms.Realms; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.chunk.Chunk; @@ -154,6 +155,10 @@ public static String getWorldName() IntegratedServer server = Minecraft.getMinecraft().getIntegratedServer(); worldName = (server != null) ? server.getFolderName() : "sp_world"; } + else if (Minecraft.getMinecraft().isConnectedToRealms()) + { + worldName = "Realms"; + } else { worldName = Minecraft.getMinecraft().getCurrentServerData().serverIP; From f5e02d8bec8b8ed46c3cbec635b628cff923d20e Mon Sep 17 00:00:00 2001 From: Vectron Date: Mon, 18 Jan 2016 16:22:19 +0100 Subject: [PATCH 102/109] Fix for coords not staying undeder the minimap --- src/main/java/mapwriter/map/MapRenderer.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java index f63fefd5..c30d21b5 100644 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -27,6 +27,8 @@ public class MapRenderer // player arrow on the rendered map public Point.Double playerArrowScreenPos = new Point.Double(0, 0); private int textOffset = 12; + private int textY = 0; + private int textX = 0; public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { @@ -225,6 +227,8 @@ private void drawIcons() private void drawStatusText() { this.textOffset = 12; + this.textY = this.mapMode.textY; + this.textX = this.mapMode.textX; drawCoords(); drawBiomeName(); drawUndergroundMode(); @@ -236,14 +240,14 @@ private void drawCoords() if (!this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[0])) { GlStateManager.pushMatrix(); - GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); + GlStateManager.translate(this.textX, this.textY, 0); if (this.mapMode.config.coordsMode.equals(MapModeConfig.coordsModeStringArray[1])) { GlStateManager.scale(0.5f, 0.5f, 1.0f); this.textOffset = (int)(this.textOffset * 0.5f); } Render.drawCentredString(0, 0, this.mapMode.textColour, "%d, %d, %d", this.mw.playerXInt, this.mw.playerYInt, this.mw.playerZInt); - this.mapMode.textY += this.textOffset; + this.textY += this.textOffset; GlStateManager.popMatrix(); } } @@ -253,14 +257,14 @@ private void drawBiomeName() if (!this.mapMode.config.biomeMode.equals(MapModeConfig.coordsModeStringArray[0])) { GlStateManager.pushMatrix(); - GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); + GlStateManager.translate(this.textX, this.textY, 0); if (this.mapMode.config.biomeMode.equals(MapModeConfig.coordsModeStringArray[1])) { GlStateManager.scale(0.5f, 0.5f, 1.0f); this.textOffset = (int)(this.textOffset * 0.5f); } Render.drawCentredString(0, 0, this.mapMode.textColour, this.mw.playerBiome); - this.mapMode.textY += this.textOffset; + this.textY += this.textOffset; GlStateManager.popMatrix(); } } @@ -270,11 +274,11 @@ private void drawUndergroundMode() if (Config.undergroundMode) { GlStateManager.pushMatrix(); - GlStateManager.translate(this.mapMode.textX, this.mapMode.textY, 0); + GlStateManager.translate(this.textX, this.textY, 0); GlStateManager.scale(0.5f, 0.5f, 1.0f); this.textOffset = (int)(this.textOffset * 0.5f); Render.drawCentredString(0, 0, this.mapMode.textColour, "underground mode"); - this.mapMode.textY += this.textOffset; + this.textY += this.textOffset; GlStateManager.popMatrix(); } } From eb71357599bad2cd18511430cfd16e47c6af66ec Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 26 Jan 2016 00:29:59 +0100 Subject: [PATCH 103/109] added the acceptedMinecraftVersions setting updated to the recomended forge version --- build.gradle | 1 + build.properties | 5 +++-- src/main/java/mapwriter/forge/MwForge.java | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index a5f22542..93e3c3e8 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,7 @@ version = config.mc_version + "-" + config.forge_version runDir = "eclipse" mappings = config.mcp_version replace '@MOD_VERSION@', config.mod_version +replace '@ACCEPTED_MC_VERSION@', config.accepted_mc_version } processResources diff --git a/build.properties b/build.properties index 9e5c395e..c9958c1c 100644 --- a/build.properties +++ b/build.properties @@ -1,8 +1,9 @@ mod_name=MapWriter mod_group=vectron mc_version=1.8.9 -forge_version=11.15.0.1707 +forge_version=11.15.1.1722 mcp_version=snapshot_20160118 mod_version=2.3.12 curse_project_id=231387 -release_type=beta \ No newline at end of file +release_type=beta +accepted_mc_version=[1.8.9] \ No newline at end of file diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java index cb2bd233..067de1b7 100644 --- a/src/main/java/mapwriter/forge/MwForge.java +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -22,7 +22,8 @@ version = Reference.VERSION, guiFactory = Reference.MOD_GUIFACTORY_CLASS, clientSideOnly = true, -updateJSON = Reference.ForgeVersionURL) +updateJSON = Reference.ForgeVersionURL, +acceptedMinecraftVersions="@ACCEPTED_MC_VERSION@") public class MwForge { From 3ded164a1425c82195b60185118f7d155b84f01d Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 26 Jan 2016 00:30:38 +0100 Subject: [PATCH 104/109] Fixed bug that setting didnt get generated with default value --- .../java/mapwriter/config/ConfigurationHandler.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/mapwriter/config/ConfigurationHandler.java b/src/main/java/mapwriter/config/ConfigurationHandler.java index 1d991d34..e141ed2e 100644 --- a/src/main/java/mapwriter/config/ConfigurationHandler.java +++ b/src/main/java/mapwriter/config/ConfigurationHandler.java @@ -20,6 +20,11 @@ public static void init(File configFile) configuration = new Configuration(configFile); setMapModeDefaults(); loadConfig(); + + configuration.get(Reference.catOptions, "overlayModeIndex", Config.overlayModeIndexDef).setShowInGui(false); + configuration.get(Reference.catOptions, "overlayZoomLevel", Config.zoomInLevelsDef).setShowInGui(false); + + } } @@ -45,7 +50,7 @@ public static void loadConfig() Config.configTextureSize = configuration.getInt("textureSize", Reference.catOptions, Config.configTextureSizeDef, 1024, 4096, "", "mw.config.textureSize"); Config.overlayModeIndex = configuration.getInt("overlayModeIndex", Reference.catOptions, Config.overlayModeIndexDef, 0, 1000, "", "mw.config.overlayModeIndex"); - Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, 0, Config.zoomInLevels, Config.zoomOutLevels, "", "mw.config.overlayZoomLevel"); + Config.overlayZoomLevel = configuration.getInt("overlayZoomLevel", Reference.catOptions, Config.overlayZoomLevelDef, Config.zoomInLevels, Config.zoomOutLevels, "", "mw.config.overlayZoomLevel"); Config.moreRealisticMap = configuration.getBoolean("moreRealisticMap", Reference.catOptions, Config.moreRealisticMapDef, "", "mw.config.moreRealisticMap"); @@ -75,9 +80,6 @@ public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent public static void setMapModeDefaults() { - configuration.get(Reference.catOptions, "overlayModeIndex", Config.overlayModeIndexDef).setShowInGui(false); - configuration.get(Reference.catOptions, "overlayZoomLevel", Config.zoomInLevelsDef).setShowInGui(false); - Config.fullScreenMap.setDefaults(); Config.largeMap.setDefaults(); Config.smallMap.setDefaults(); From 220e7d23224ff4359e62e602e75559f986a36ed6 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 26 Jan 2016 00:42:14 +0100 Subject: [PATCH 105/109] Fix for markers not reloading when world is loaded --- src/main/java/mapwriter/map/MarkerManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java index b4e25b9c..3ac5ee29 100644 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -159,12 +159,12 @@ public Marker stringToMarker(String s) public void addMarker(Marker marker) { this.markerList.add(marker); - this.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); } public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); + this.save(WorldConfig.getInstance().worldConfiguration, Reference.catMarkers); } // returns true if the marker exists in the arraylist. From e117568af65743441933b31c0412772303f29586 Mon Sep 17 00:00:00 2001 From: Vectron Date: Tue, 26 Jan 2016 01:27:20 +0100 Subject: [PATCH 106/109] Allow for all unicode letters in markers and world names --- src/main/java/mapwriter/util/Reference.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/mapwriter/util/Reference.java b/src/main/java/mapwriter/util/Reference.java index 038a3d42..4b0714f0 100644 --- a/src/main/java/mapwriter/util/Reference.java +++ b/src/main/java/mapwriter/util/Reference.java @@ -26,9 +26,9 @@ public final class Reference public static final String PlayerTrailName = "player"; - public static final Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - public static final Pattern patternInvalidChars2 = Pattern.compile("[^a-zA-Z0-9_ -]"); - + public static final Pattern patternInvalidChars = Pattern.compile("[^\\p{L}\\p{Nd}_]"); + public static final Pattern patternInvalidChars2 = Pattern.compile("[^\\p{L}\\p{Nd}_ -]"); + public static final String catWorld = "world"; public static final String catMarkers = "markers"; public static final String worldDirConfigName = "mapwriter.cfg"; From b5913f36d198cb767cd4ed143df4212f58d71b5c Mon Sep 17 00:00:00 2001 From: muink Date: Tue, 26 Jan 2016 16:50:01 +0800 Subject: [PATCH 107/109] Chinese language file for 1.8 --- .../assets/mapwriter/lang/zh_CN.lang | 186 ++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 src/main/resources/assets/mapwriter/lang/zh_CN.lang diff --git a/src/main/resources/assets/mapwriter/lang/zh_CN.lang b/src/main/resources/assets/mapwriter/lang/zh_CN.lang new file mode 100644 index 00000000..191d8de4 --- /dev/null +++ b/src/main/resources/assets/mapwriter/lang/zh_CN.lang @@ -0,0 +1,186 @@ +# Keys +key.mw_open_gui=打开地图主界面 +key.mw_new_marker=添加新导航点 +key.mw_next_map_mode=下一种显示模式 +key.mw_next_marker_group=下一组导航点 +key.mw_teleport=传送到选定导航点 +key.mw_zoom_in=地图放大 +key.mw_zoom_out=地图缩小 +key.mw_underground_mode=洞穴地图模式 + +#Config +mw.configgui.ctgy.general=常规 +mw.configgui.ctgy.general.tooltip=打开常规选项 +mw.configgui.ctgy.fullScreenMap=全屏地图 +mw.configgui.ctgy.fullScreenMap.tooltip=打开全屏地图选项 +mw.configgui.ctgy.largeMap=大地图 +mw.configgui.ctgy.largeMap.tooltip=打开大地图选项 +mw.configgui.ctgy.smallMap=小地图 +mw.configgui.ctgy.smallMap.tooltip=打开小地图选项 + +#Config Global +mw.config.linearTextureScaling=线性缩放 +mw.config.linearTextureScaling.tooltip=启用将使用线性缩放方式缩放地图. (否则将使用临近(保留硬边缘)缩放) +mw.config.useSavedBlockColours=使用已存的方块颜色 +mw.config.useSavedBlockColours.tooltip=启用它将防止方块颜色重载并允许你自定义颜色. +mw.config.teleportEnabled=传送 +mw.config.teleportEnabled.tooltip=允许传送玩家到地图上的指定位置 +mw.config.teleportCommand=传送命令 +mw.config.teleportCommand.tooltip=此命令用于传送玩家 + +mw.config.maxChunkSaveDistSq=最大绘图距离 +mw.config.maxChunkSaveDistSq.tooltip=以玩家为中心的方形绘图范围 +mw.config.mapPixelSnapEnabled=地图像素捕捉 +mw.config.mapPixelSnapEnabled.tooltip=取整目标到最近的像素边界的材质, 这使得地图在缩放级别为0时看起来不那么模糊 +mw.config.maxDeathMarkers=死亡标记数量 +mw.config.maxDeathMarkers.tooltip=死亡标记的最大数值 +mw.config.chunksPerTick=区块更新 +mw.config.chunksPerTick.tooltip=设置每个游戏刻的区块更新次数 +mw.config.saveDirOverride=指定保存目录 +mw.config.saveDirOverride.tooltip=指定MapWriter用于保存图像和区域文件的目录 +mw.config.portNumberInWorldNameEnabled=在世界名称中追加端口号 +mw.config.portNumberInWorldNameEnabled.tooltip=禁用将停止追加端口号到多人游戏的世界名称 +mw.config.undergroundMode=洞穴模式 +mw.config.undergroundMode.tooltip=启用洞穴模式 +mw.config.regionFileOutputEnabledSP=区域文件导出(单人) +mw.config.regionFileOutputEnabledSP.tooltip=禁用将取消在单人世界保存区域文件 (mca文件). 防止区域重建 +mw.config.regionFileOutputEnabledMP=区域文件导出(多人) +mw.config.regionFileOutputEnabledMP.tooltip=禁用将取消在多人世界保存区域文件 (mca文件). 防止区域重建 +mw.config.backgroundTextureMode=地图背景模式 +mw.config.backgroundTextureMode.tooltip=设置地图背景类型 +mw.config.backgroundTextureMode.none=无 +mw.config.backgroundTextureMode.static=静态线框 +mw.config.backgroundTextureMode.panning=区块线框 +mw.config.zoomOutLevels=缩小量 +mw.config.zoomOutLevels.tooltip=单次最大可缩小量. 较大的值会降低性能. +mw.config.zoomInLevels=放大量 +mw.config.zoomInLevels.tooltip=单次最大可放大量. 不影响性能. +mw.config.textureSize=材质尺寸 +mw.config.textureSize.tooltip=设置地图的材质尺寸 +mw.config.moreRealisticMap=真实地图 +mw.config.moreRealisticMap.tooltip=允许使用高度算法, 使地图看起来更逼真 +mw.config.newMarkerDialog=新导航点对话框 +mw.config.newMarkerDialog.tooltip=启用它来使用新导航点对话框 +mw.config.drawMarkersInWorld=在世界中显示导航点 +mw.config.drawMarkersInWorld.tooltip=在导航点位置上显示一道可见的光柱 +mw.config.drawMarkersNameInWorld=在世界中显示导航点名称 +mw.config.drawMarkersNameInWorld.tooltip=在导航点位置上绘制名称标签 +mw.config.drawMarkersDistanceInWorld=在世界中显示导航点距离 +mw.config.drawMarkersDistanceInWorld.tooltip=在导航点位置上绘制距离标签 + +#Config map +mw.config.map.enabled=地图启用 +mw.config.map.enabled.tooltip=禁用其将无法显示此地图 +mw.config.map.playerArrowSize=玩家箭头尺寸 +mw.config.map.playerArrowSize.tooltip=玩家箭头在地图中的尺寸 +mw.config.map.markerSize=导航点尺寸 +mw.config.map.markerSize.tooltip=导航点在地图中的尺寸 +mw.config.map.alphaPercent=地图透明度 +mw.config.map.alphaPercent.tooltip=地图透明度. 0%-100% +mw.config.map.heightPercent=地图百分比尺寸 +mw.config.map.heightPercent.tooltip=如果左右边距或上下边距被忽略. 设置地图尺寸为屏幕高度的百分比. +mw.config.map.marginTop=上边距 +mw.config.map.marginTop.tooltip=距屏幕上方以像素为单位的距离 +mw.config.map.marginBottom=下边距 +mw.config.map.marginBottom.tooltip=距屏幕下方以像素为单位的距离 +mw.config.map.marginLeft=左边距 +mw.config.map.marginLeft.tooltip=距屏幕左侧以像素为单位的距离 +mw.config.map.marginRight=右边距 +mw.config.map.marginRight.tooltip=距屏幕右侧以像素为单位的距离 +mw.config.map.rotate=地图旋转 +mw.config.map.rotate.tooltip=启用地图旋转, 仅圆形地图有效 +mw.config.map.circular=地图样式 +mw.config.map.circular.tooltip=True = 圆形地图, false = 方形地图 +mw.config.map.borderMode=绘制边框 +mw.config.map.borderMode.tooltip=绘制地图边框 +mw.config.map.trailMarkerSize=路径标记尺寸 +mw.config.map.trailMarkerSize.tooltip=地图中的路径标记尺寸 +mw.config.map.coordsMode=显示坐标 +mw.config.map.coordsMode.tooltip=按大小尺寸切换地图下的坐标 +mw.config.map.biomeMode=显示生物群系 +mw.config.map.biomeMode.tooltip=按大小尺寸切换小地图下的生物群系名称 +mw.config.map.coordsMode.disabled=禁用 +mw.config.map.coordsMode.small=小 +mw.config.map.coordsMode.large=大 +mw.config.map.position=地图位置 +mw.config.map.position.tooltip=地图位置 +mw.config.map.position.topRight=右上角 +mw.config.map.position.topLeft=左上角 +mw.config.map.position.botRight=右下角 +mw.config.map.position.botLeft=左下角 + +#Gui +mw.gui.mwgui.help=帮助 +mw.gui.mwgui.options=选项 +mw.gui.mwgui.dimension=世界层面: %d +mw.gui.mwgui.group.1=导航组: %s +mw.gui.mwgui.group.2=group +mw.gui.mwgui.overlay=叠加层: %s +mw.gui.mwgui.keys=按键 +mw.gui.mwgui.newversion=新版本: %s +mw.gui.mwgui.helptext.1=左击并拖动或用方向键移动地图. +mw.gui.mwgui.helptext.2=滚动鼠标滚轮或使用mod设定的放大缩小键缩放地图. +mw.gui.mwgui.helptext.3=右键标记新导航点 +mw.gui.mwgui.helptext.4=左击并拖动导航点来移动它. +mw.gui.mwgui.helptext.5=滚动鼠标滚轮来选择导航点颜色. +mw.gui.mwgui.helptext.6=滚动鼠标滚轮来选择目标在世界层面或导航组中. +mw.gui.mwgui.helptext.7=右击导航点或在导航点列表中右击它来修改其. +mw.gui.mwgui.helptext.8=双击列表中的导航点则以所选导航点为中心显示地图 +mw.gui.mwgui.helptext.9=左击列表中的导航点以选中它 +mw.gui.mwgui.helptext.nextmarkergroup=下一组导航点 +mw.gui.mwgui.helptext.deletemarker=删除所选导航点 +mw.gui.mwgui.helptext.cyclecolour=改变所选导航点颜色 +mw.gui.mwgui.helptext.centermap=以玩家为中心显示地图 +mw.gui.mwgui.helptext.centermapplayer=以所选导航点为中心显示地图 +mw.gui.mwgui.helptext.selectnextmarker=选择下一个导航点 +mw.gui.mwgui.helptext.teleport=传送到所选导航点或光标位置 +mw.gui.mwgui.helptext.savepng=保存地图可见区域为PNG图像 +mw.gui.mwgui.helptext.regenerate=从区域文件重新生成地图可见区域 +mw.gui.mwgui.helptext.undergroundmap=洞穴地图模式 +mw.gui.mwgui.helptext.markerlist=显示导航点列表 +mw.gui.mwgui.status.biome=生物群系: %s +mw.gui.mwgui.status.cursor=光标位置: (%d, %d, %d) +mw.gui.mwgui.status.cursorNoY=光标位置: (%d, ?, %d) +mw.gui.mwgui.group=group +mw.gui.mwgui.chatmsg.regenmap=重新构建 %dx%d 面积区域, 起始于坐标 (%d, %d) +mw.gui.mwgui.chatmsg.merge=写入到 '%s' + +mw.gui.mwguidimensiondialog.title=设置世界层面为 +mw.gui.mwguidimensiondialog.error=无效的世界层面 + +mw.gui.mwguimarkerdialog.title.new=导航点名称 +mw.gui.mwguimarkerdialog.title.edit=编辑导航点名称 +mw.gui.mwguimarkerdialog.error=导航点名称不能为空 +mw.gui.mwguimarkerdialog.title.group=导航组 +mw.gui.mwguimarkerdialog.error.group=导航组名称不能为空 +mw.gui.mwguimarkerdialog.title.x=X坐标 +mw.gui.mwguimarkerdialog.error.x=无效值 +mw.gui.mwguimarkerdialog.title.y=Y坐标 +mw.gui.mwguimarkerdialog.error.y=无效值 +mw.gui.mwguimarkerdialog.title.z=Z坐标 +mw.gui.mwguimarkerdialog.error.z=无效值 + +mw.gui.mwguimarkerdialognew.title.new=添加新导航点 +mw.gui.mwguimarkerdialognew.title.edit=编辑导航点 +mw.gui.mwguimarkerdialognew.editMarkerName=名称 +mw.gui.mwguimarkerdialognew.editMarkerGroup=导航组 +mw.gui.mwguimarkerdialognew.editMarkerX=X +mw.gui.mwguimarkerdialognew.editMarkerY=Y +mw.gui.mwguimarkerdialognew.editMarkerZ=Z +mw.gui.mwguimarkerdialognew.editMarkerColor=颜色 +mw.gui.mwguimarkerdialognew.title=传送目标点高度 +mw.gui.mwguimarkerdialognew.error=无效高度 + +mw.gui.ScrollableColorSelector.Red=红 +mw.gui.ScrollableColorSelector.Green=绿 +mw.gui.ScrollableColorSelector.Blue=蓝 + +#task +mw.task.mergetask.chatmsg.merge.done=成功写入图像到目录 %s +mw.task.mergetask.chatmsg.merge.error=写入错误: 无法写入图像到目录 %s +mw.task.rebuildregionstask.chatmsg.rebuild.compleet=重新构建任务完成 + +#messages +mw.msg.tp.disabled=传送已在配置页面中被禁用 +mw.msg.tp.dimError=无法传送到不同层面的导航点 +mw.msg.warp.error=teleport command is set to 'warp', can only warp to markers \ No newline at end of file From b3a07e832e3c2f7ebf721f59aa6da9f67762f363 Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 28 Jan 2016 12:10:37 +0100 Subject: [PATCH 108/109] updated version for release --- build.properties | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/build.properties b/build.properties index c9958c1c..ea90dcdc 100644 --- a/build.properties +++ b/build.properties @@ -1,9 +1,9 @@ -mod_name=MapWriter -mod_group=vectron -mc_version=1.8.9 -forge_version=11.15.1.1722 -mcp_version=snapshot_20160118 -mod_version=2.3.12 -curse_project_id=231387 -release_type=beta +mod_name=MapWriter +mod_group=vectron +mc_version=1.8.9 +forge_version=11.15.1.1722 +mcp_version=snapshot_20160118 +mod_version=2.3.13 +curse_project_id=231387 +release_type=beta accepted_mc_version=[1.8.9] \ No newline at end of file From f8942c1b518f803ddffd5f024643b2c57d4d321b Mon Sep 17 00:00:00 2001 From: Vectron Date: Thu, 28 Jan 2016 12:31:17 +0100 Subject: [PATCH 109/109] Changed release type to release --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index ea90dcdc..7243a290 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ forge_version=11.15.1.1722 mcp_version=snapshot_20160118 mod_version=2.3.13 curse_project_id=231387 -release_type=beta +release_type=release accepted_mc_version=[1.8.9] \ No newline at end of file